patientModule.directive("chargeOrderPrintTemplateView", ["$log", "$timeout", "$window", "$sce", function(n, t, i, r) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/components/charge-order-print-template-view.html",
        link: function(n, i) {
            var u = null,
                e = function() {
                    var t = i.find(".template-status");
                    if (t.length > 0) {
                        var r = t.attr("chargeOrderInited") == "true",
                            u = t.attr("templateLoaded") == "true",
                            f = t.attr("templateReplaced") == "true";
                        return r ? u && r && !f ? (n.initTemplateReplace(), !1) : u && r && f ? !0 : !1 : (n.initCurrentChargeOrder(), !1)
                    }
                    return !1
                },
                f = function() {
                    o();
                    u = t(s, 3e3)
                },
                o = function() {
                    u && t.cancel(u)
                },
                s = function() {
                    var o = e(),
                        u;
                    o ? (u = "", n.systemConfig.isPrivate || (u = i.find("#" + n.templateType).html()), n.printInfo = r.trustAsHtml(u), t(function() {
                        i.find("#printBtn").click();
                        n.returnPrintInfo()
                    }, 300)) : f()
                };
            (function() {
                n.initPrintType();
                n.printInfo = "";
                n.initConfigData(function() {
                    f()
                })
            })()
        }
    }
}]);
patientModule.controller("chargeOrderPrintTemplateCtrl", ["$log", "$scope", "$q", "host", "practiceSvc", "appointmentSvc", "$modalInstance", "loginContext", "chargeUtil", function(n, t, i, r, u, f, e, o, s) {
    var l = function() {
            e.close(t.printInfo)
        },
        h = function(n) {
            e.dismiss(n)
        },
        a = function() {
            var n = i.defer();
            return r.chargeOrder.feeType == 2 ? y(n) : r.chargeOrder.feeType == 1 || r.chargeOrder.feeType == 3 ? v(n) : c(n), n.promise
        },
        v = function(n) {
            u.getRefundTemplate().success(function(i) {
                t.systemConfig.ConfigName = "patientReimburseCharge";
                i ? (t.hasReimburseTemplate = !0, t.systemConfig.templateStyle = i.templateStyle, t.systemConfig.templateType = i.templateCode, t.templateType = i.templateCode, t.systemConfig.isPrivate = i.isPrivateTemplate, t.privateTemplate = i, n.resolve()) : (t.hasReimburseTemplate = !1, t.templateType = "RefundTemplate", t.systemConfig.templateType = t.templateType, t.systemConfig.isPrivate = !1, t.privateTemplate = null, n.resolve())
            })
        },
        y = function(n) {
            u.getOverdueTemplate().success(function(i) {
                i ? (t.hasOverdueTemplate = !0, t.systemConfig.templateStyle = i.templateStyle, t.systemConfig.isPrivate = i.isPrivateTemplate, t.systemConfig.ConfigName = "patientCharge", t.systemConfig.templateType = i.templateCode, t.templateType = i.templateCode, n.resolve()) : (t.hasOverdueTemplate = !1, c(n))
            })
        },
        c = function(n) {
            t.systemConfig.ConfigName = t.printType;
            t.printComment = t.printType == "patientSimpleCharge" ? "patientSimpleChargePrint" : "patientChargePrint";
            t.systemConfig.Coments = t.printComment;
            u.getSystemConfig(t.systemConfig).success(function(i) {
                i ? (t.systemConfig.isHide = !1, t.templateType = i.configValue, t.tempelate = i.configValue, u.getTemplateByCode(t.tempelate).success(function(i) {
                    t.systemConfig.templateStyle = i.templateStyle;
                    t.systemConfig.isPrivate = i.isPrivateTemplate;
                    t.systemConfig.templateType = t.templateType;
                    n.resolve()
                })) : (t.systemConfig.isHide = !0, h("请配置打印模板！"))
            })
        },
        p = function() {
            var n = i.defer();
            return t.office = {}, u.getOffice(o.officeId).success(function(i) {
                t.office = i;
                t.systemConfigs = t.office.systemConfigs;
                t.systemConfigs || (t.systemConfigs = {});
                n.resolve()
            }), n.promise
        },
        w = function() {
            var n = i.defer();
            return t.BusinessDate = {}, u.getDefaultWorkTime(o.officeId).success(function(i) {
                i.startTimeStr = i.startTime;
                i.endTimeStr = i.endTime;
                t.BusinessDate = i;
                n.resolve()
            }), n.promise
        },
        b = function() {
            var n = i.defer();
            return f.getAppointment(r.chargeOrder.appointmentId).success(function(i) {
                t.visitingTime = i;
                n.resolve()
            }), n.promise
        },
        k = function(n) {
            i.all([p(), w(), b(), a()]).then(function() {
                n && n()
            })
        },
        d = function() {
            t.currentChargeOrder = angular.copy(r.chargeOrder);
            t.patient = angular.copy(r.patient)
        },
        g = function() {
            t.isChargeSaved = !0
        },
        nt = function() {
            t.printType = r.chargeOrder.feeType == 1 || r.chargeOrder.feeType == 3 ? "patientReimburseCharge" : r.chargeOrder.orderType == "simple" || r.chargeOrder.orderType == "简易" ? "patientSimpleCharge" : "patientCharge"
        };
    t.priceToFixed = function(n) {
            return Ares.priceToFixed(n)
        },
        function() {
            t.arabia_to_Chinese = s.arabia_to_Chinese;
            t.arabia_all_to_Chinese = s.arabia_all_to_Chinese;
            t.returnPrintInfo = l;
            t.returnErrorInfo = h;
            t.initCurrentChargeOrder = d;
            t.initTemplateReplace = g;
            t.systemConfig = {};
            t.initPrintType = nt;
            t.initConfigData = k
        }()
}]);
clinicalModule.controller("patientBarcodeBatchPrintCtrl", ["$log", "$scope", "$q", "aresNotification", function(n, t) {
    "use strict";
    (function() {
        t.printElementIds = new Array(30).fill("").map((n, t) => "privateBarcode" + (t + 1))
    })()
}]);
clinicalModule.directive("patientBarcodeBatchPrintView", ["$log", "$timeout", "$q", "patientSvc", "printTemplateUtil", "$compile", function(n, t, i, r, u, f) {
    "use strict";
    return {
        restrict: "E",
        controller: "patientBarcodeBatchPrintCtrl",
        replace: !0,
        scope: {
            patientInfo: "=?"
        },
        link: function(n, t) {
            var o = function() {
                    var r, u, i;
                    for (r in n.printElementIds) u = "#" + n.printElementIds[r], i = t.find(u), i.html(""), i.kendoBarcode({
                        value: n.patientInfo.privateId,
                        type: "code128",
                        width: t.find(".patient-barcode-print").width(),
                        height: i.height()
                    })
                },
                i = function(t) {
                    n.patientMobile = "";
                    r.getMobileByPatientId(t).success(function(t) {
                        t.length > 0 && (n.patientMobile = t[0].mobile)
                    })
                },
                e = function() {
                    u.getTemplateByCode("mlhzbq").then(function(t) {
                        n.printTemplate = t
                    });
                    n.printTemplate || u.getTemplateByCode("hzbq").then(function(t) {
                        n.printTemplate = t
                    })
                };
            (function() {
                n.$watch("patientInfo", function() {
                    n.patientInfo && (i(n.patientInfo.id), e())
                });
                n.$watch("printTemplate", function() {
                    if (n.printTemplate) {
                        var i = f(n.printTemplate.templateContent)(n);
                        t.html(i)
                    }
                })
            })()
        }
    }
}]);
clinicalModule.directive("patientBarcodePrintView", ["$log", "$timeout", "$q", "patientSvc", function() {
    "use strict";
    return {
        restrict: "E",
        templateUrl: "/app/patient/components/patient-barcode-print/patient-barcode-print-view.html",
        scope: {
            patientInfo: "=?"
        },
        link: function(n, t) {
            var i = function() {
                t.find("#privateIdBarcode").html("");
                t.find("#privateIdBarcode").kendoBarcode({
                    value: n.patientInfo.privateId,
                    type: "code128",
                    width: 430,
                    height: 100
                })
            };
            (function() {
                n.$watch("patientInfo", function() {
                    n.patientInfo && i()
                })
            })()
        }
    }
}]);
patientModule.directive("patientImageView", ["$log", "$timeout", "$interval", "$modal", "eventAggregator", "aresDialog", function(n, t, i, r, u, f) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/components/patient-image/patient-image-view.html",
        scope: {
            patient: "=",
            picture: "=",
            enableEdit: "=",
            enableTakePhoto: "=",
            isViewModel: "=?"
        },
        controller: "PatientImageCtrl",
        link: function(n, i) {
            var o = function() {
                    if (!n.isViewModel) {
                        var t = r.open({
                            animation: !0,
                            backdrop: "static",
                            template: "<patient-photo-view><\/patient-photo-view>",
                            controller: "PatientPhotoCtrl",
                            size: "md",
                            resolve: {
                                host: function() {
                                    return {
                                        patientId: n.patient.id,
                                        picture: n.picture ? angular.copy(n.picture) : {},
                                        event: n.enableEdit ? "edit" : "load"
                                    }
                                }
                            }
                        });
                        t.result.then(function(t) {
                            if (t.id) n.updatePatientPicture(t).then(function() {
                                e(t)
                            });
                            else if (n.picture && n.picture.id) {
                                var i = {
                                    id: 0,
                                    filePath: null
                                };
                                n.updatePatientPicture(i).then(function() {
                                    e(i)
                                })
                            }
                        })
                    }
                },
                e = function(t) {
                    n.patient.imgSrc = t.filePath;
                    n.patient.pictureId = t.id;
                    n.picture ? (n.picture.id = t.id, n.picture.filePath = t.filePath) : n.picture = t;
                    u.publish(u.events.PatientChanged, n.patient, "PatientImageCtrl")
                },
                s = function() {
                    i.find("#patient-photo-div").hover(function() {
                        var r = i.find(this);
                        r.hasClass("not-allow-action") || t(function() {
                            n.isPatientPhotoHovered = !0
                        })
                    }, function() {
                        var r = i.find(this);
                        r.hasClass("not-allow-action") || t(function() {
                            n.isPatientPhotoHovered = !1
                        })
                    })
                },
                h = function() {
                    f.confirm("确认", "确定删除患者头像？").then(function() {
                        var t = {
                            id: 0,
                            filePath: null
                        };
                        n.updatePatientPicture(t).then(function() {
                            e(t)
                        })
                    })
                };
            (function() {
                n.isPatientPhotoHovered = !1;
                n.onClickPhoto = o;
                n.onDeletePatientPicture = h;
                s()
            })()
        }
    }
}]);
patientModule.controller("PatientImageCtrl", ["$log", "$scope", "$q", "patientSvc", "patientUtil", function(n, t, i, r, u) {
    "use strict";
    var f = function(n) {
        var f = i.defer();
        return r.updatePatientPicture(t.patient.id, n.id).success(function() {
            u.createFaceRecognition(t.patient.id);
            f.resolve()
        }).error(function() {
            f.reject()
        }), f.promise
    };
    (function() {
        t.updatePatientPicture = f
    })()
}]);
patientModule.directive("patientInfoBaseBlockView", ["$log", "$timeout", "$modal", "aresDialog", "aresNotification", function() {
    "use strict";
    return {
        scope: !1,
        restrict: "E",
        replace: !0,
        controller: "PatientInfoBaseBlockCtrl",
        templateUrl: "/app/patient/components/patient-info-base-block/patient-info-base-block-view.html",
        link: function(n, t) {
            var i = function() {
                var r = t.find("#province"),
                    u, n, f, i, e;
                r && (u = r.data("kendoDropDownList"), u.value(null));
                n = t.find("#city");
                n && (f = n.data("kendoDropDownList"), f.value(null));
                i = t.find("#district");
                i && (e = i.data("kendoDropDownList"), e.value(null))
            };
            (function() {
                n.clearPatientDistrict = i
            })()
        }
    }
}]);
patientModule.controller("PatientInfoBaseBlockCtrl", ["$log", "$scope", "$q", "aresNotification", "practiceSvc", "officeOptionUtil", "dataDicSvc", function(n, t, i, r, u, f, e) {
    "use strict";
    var o = function() {
            u.getItemTypes("mobileAttribute").success(function(n) {
                t.mobileAttribute = n
            });
            u.getItemTypes("phoneNumberAttribute").success(function(n) {
                t.phoneNumberAttribute = n
            });
            f.setIsReadIdentityCardEnabled(t)
        },
        s = function(n) {
            e.officeDic.load().then(function(i) {
                var r = _.find(i, function(t) {
                    return t.id === n
                });
                r && (t.officeName = r.abbreviation)
            })
        };
    (function() {
        o();
        t.officeName = "";
        t.$watch("patient", function() {
            t.patient && s(t.patient.officeId)
        })
    })()
}]);
patientModule.directive("patientInfoClientRelationBlockView", ["$log", "$timeout", "$modal", "aresDialog", "aresNotification", "patientSvc", "dataDicSvc", "providerSvc", function(n, t, i, r, u, f, e, o) {
    "use strict";
    return {
        scope: !1,
        restrict: "E",
        replace: !0,
        controller: "PatientInfoClientRelationBlockCtrl",
        templateUrl: "/app/patient/components/patient-info-client-relation-block/patient-info-client-relation-block-view.html",
        link: function(n, t) {
            var i = null,
                u = function() {
                    var t = _.find(n.doctors, function(t) {
                        return n.patient.dutyDoctorId == t.id
                    });
                    n.patient.dutyDoctorName = t ? t.name : "";
                    r();
                    i.setDataSource(n.advisors)
                },
                s = function() {
                    var t = _.find(n.consultants, function(t) {
                        return n.patient.consultantId == t.id
                    });
                    n.patient.consultantName = t ? t.name : "";
                    r();
                    i.setDataSource(n.advisors)
                },
                r = function() {
                    n.advisors = [];
                    n.patient.dutyDoctorId && n.advisors.push({
                        name: n.patient.dutyDoctorName,
                        id: n.patient.dutyDoctorId
                    });
                    n.patient.consultantId && n.advisors.push({
                        name: n.patient.consultantName,
                        id: n.patient.consultantId
                    });
                    n.advisors.some(function(t) {
                        return t.id == n.patient.advisorId
                    }) || (n.patient.advisorId = null, n.patient.advisorName = null)
                },
                h = function() {
                    f.getClientPatient(n.patientId).success(function(u) {
                        n.patient.advisorId = u.advisorId;
                        n.patient.advisorName = u.advisorName;
                        n.patient.dutyDoctorId = u.dutyDoctorId;
                        n.patient.dutyDoctorName = u.dutyDoctorName;
                        n.patient.consultantId = u.consultantId;
                        n.patient.consultantName = u.consultantName;
                        n.patient.extension.developerId = u.developerId;
                        n.patient.extension.developerName = u.developerName;
                        n.patient.extension.onlineConsultantName = u.onlineConsultantName;
                        n.patient.extension.onlineConsultantId = u.onlineConsultantId;
                        e.attendantDic.loadActive().then(function(t) {
                            n.attendants = _.filter(t, function(n) {
                                return n.show != !1
                            });
                            u.attendantId && o.getName(u.attendantId).then(function(t) {
                                n.patient.attendantName = t || ""
                            })
                        });
                        r();
                        i = t.find("#advisorId").kendoDropDownList({
                            dataSource: n.advisors,
                            optionLabel: "未指定专属顾问",
                            dataTextField: "name",
                            dataValueField: "id",
                            filter: "contains",
                            value: n.patient.advisorId,
                            change: function(t) {
                                var i = this.dataItem(t.item);
                                n.patient.advisorId = i[this.options.dataValueField] || null;
                                n.patient.advisorName = i[this.options.dataTextField] || null
                            }
                        }).data("kendoDropDownList")
                    })
                };
            (function() {
                n.onChangeDutyDoctor = u;
                n.onChangeConsultant = s;
                n.registerOnEditingCallBackMethod("infoClientRelation", h)
            })()
        }
    }
}]);
patientModule.controller("PatientInfoClientRelationBlockCtrl", ["$log", "$scope", "$q", "aresNotification", function() {
    "use strict";
    (function() {})()
}]);
patientModule.directive("patientInfoContactView", ["$log", "$timeout", "$q", "$modal", "aresDialog", "aresNotification", "patientUtil", "baiduAreaSvc", "dataDicSvc", "patientSvc", "permissionProvider", "practiceSvc", "loginContext", function(n, t, i, r, u, f, e, o, s, h, c, l, a) {
    "use strict";
    return {
        scope: !1,
        restrict: "E",
        replace: !0,
        controller: "PatientInfoContactCtrl",
        templateUrl: "/app/patient/components/patient-info-contact/patient-info-contact-view.html",
        link: function(n, r) {
            var b = function() {
                    if (n.infoBase.isEdit) {
                        var t = n.patient.familyAddress;
                        t && t.province ? p() : s.officeInfoDic.load().then(function(n) {
                            if (n.province) {
                                var t = {
                                    province: n.province,
                                    city: n.city,
                                    district: n.district
                                };
                                p(t)
                            } else p()
                        })
                    }
                },
                p = function(t) {
                    v(1, "", 1).then(function(i) {
                        n.currentProvinces = i;
                        n.currentCitys = [];
                        n.currentDistricts = [];
                        var e, r, f;
                        t && n.patient && (n.patient.familyAddress = n.patient.familyAddress ? n.patient.familyAddress : {}, t.province && (n.patient.familyAddress.province = t.province), t.city && (n.patient.familyAddress.city = t.city), t.district && (n.patient.familyAddress.district = t.district));
                        n.patient && n.patient.familyAddress && n.patient.familyAddress.province && (e = w(n.currentProvinces, n.patient.familyAddress.province));
                        u("#province", n.currentProvinces, e, k);
                        n.patient && n.patient.familyAddress && n.patient.familyAddress.province ? v(e, n.patient.familyAddress.province, 2).then(function(t) {
                            n.currentCitys = t;
                            r = w(n.currentCitys, n.patient.familyAddress.city);
                            u("#city", n.currentCitys, r, y);
                            n.patient && n.patient.familyAddress && n.patient.familyAddress.city ? v(r, n.patient.familyAddress.city, 3).then(function(t) {
                                n.currentDistricts = t;
                                f = w(n.currentDistricts, n.patient.familyAddress.district);
                                u("#district", n.currentDistricts, f, undefined)
                            }) : u("#district", n.currentDistricts, f, undefined)
                        }) : (u("#city", n.currentCitys, r, y), u("#district", n.currentDistricts, f, undefined))
                    })
                },
                u = function(i, u, f, e) {
                    f || (f = "");
                    var o = r.find(i),
                        s = o.kendoDropDownList({
                            dataSource: u,
                            optionLabel: "请选择",
                            dataTextField: "areaName",
                            dataValueField: "areaCode",
                            value: f,
                            select: function(i) {
                                var u = this.dataItem(i.item)[this.options.dataValueField] || null,
                                    r = this.dataItem(i.item)[this.options.dataTextField] || null;
                                r == "请选择" && (r = "");
                                t(function() {
                                    e ? e(u, r) : n.patient.familyAddress.district = r
                                })
                            }
                        }).data("kendoDropDownList")
                },
                k = function(t, i) {
                    n.patient.familyAddress || (n.patient.familyAddress = {});
                    i != n.patient.familyAddress.province && (n.patient.familyAddress.city = "", n.patient.familyAddress.district = "");
                    n.patient.familyAddress.province = i;
                    i && i != "" ? v(t, i, 2).then(function(t) {
                        n.currentCitys = t;
                        n.currentDistricts = [];
                        u("#city", n.currentCitys, undefined, y);
                        u("#district", n.currentDistricts, undefined, undefined)
                    }) : (n.currentCitys = [], n.currentDistricts = [], u("#city", n.currentCitys, undefined, y), u("#district", n.currentDistricts, undefined, undefined))
                },
                y = function(t, i) {
                    i != n.patient.familyAddress.city && (n.patient.familyAddress.district = "");
                    n.patient.familyAddress.city = i;
                    i && i != "" ? v(t, i, 3).then(function(t) {
                        n.currentDistricts = t;
                        u("#district", n.currentDistricts, undefined, undefined)
                    }) : (n.currentDistricts = [], u("#district", n.currentDistricts, undefined, undefined))
                },
                w = function(n, t) {
                    var r = 1,
                        i = _.filter(n, {
                            areaName: t
                        });
                    return i && i.length > 0 && (r = i[0].areaCode), r
                },
                v = function(t, r, u) {
                    var f = i.defer(),
                        e;
                    return u == 2 && (r == "北京市" || r == "天津市" || r == "上海市" || r == "重庆市" || r == "澳门特别行政区" || r == "香港特别行政区") && (e = [{
                        areaName: r,
                        areaCode: t
                    }], f.resolve(e)), n.criteria = {
                        areaCode: t,
                        areaType: u
                    }, o.getSubBaiduAreas(n.criteria).success(function(n) {
                        f.resolve(n)
                    }).error(function(n) {
                        f.reject(n)
                    }), f.promise
                },
                d = function(t) {
                    var r = i.defer();
                    return h.getPatientAddress(t).success(function(t) {
                        n.patient.familyAddress = t ? t : {};
                        r.resolve(n.patient.familyAddress)
                    }), r.promise
                },
                g = function() {
                    var t = e.editSysitemContent("手机号码属性");
                    t.result.then(function() {
                        l.getItemTypes("mobileAttribute").success(function(t) {
                            var i, r;
                            for (n.mobileAttribute = t, i = 0; i < n.patient.mobileList.length; i++) r = _.find(n.mobileAttribute, function(t) {
                                return t.itemName == n.patient.mobileList[i].mobileType
                            }), r == null && (n.patient.mobileList[i].mobileType = "")
                        })
                    })
                },
                nt = function() {
                    var t = e.editSysitemContent("电话号码属性");
                    t.result.then(function() {
                        l.getItemTypes("phoneNumberAttribute").success(function(t) {
                            var i, r;
                            for (n.phoneNumberAttribute = t, i = 0; i < n.patient.phoneNumberList.length; i++) r = _.find(n.phoneNumberAttribute, function(t) {
                                return t.itemName == n.patient.phoneNumberList[i].mobileType
                            }), r == null && (n.patient.phoneNumberList[i].mobileType = "")
                        })
                    })
                },
                tt = function() {
                    if (n.patient.mobileList.length == 3) {
                        f.error("同个患者最多添加三个手机号码！");
                        return
                    }
                    if (n.patient.mobileList[n.patient.mobileList.length - 1].mobile == "") {
                        f.error("请设置正确的手机号码及属性！");
                        return
                    }
                    if (n.patient.mobileList[n.patient.mobileList.length - 1].mobileType == "") {
                        f.error("请设置正确的手机号码及属性！");
                        return
                    }
                    var t = {
                        mobile: "",
                        patientId: n.patient.id,
                        attributes: "mobile",
                        mobileType: "",
                        displayOrder: n.patient.mobileList.length + 1
                    };
                    n.patient.mobileList.push(t)
                },
                it = function() {
                    if (n.patient.phoneNumberList.length == 2) {
                        f.error("同个患者最多添加两个电话号码！");
                        return
                    }
                    if (n.patient.phoneNumberList[n.patient.phoneNumberList.length - 1].mobile == "") {
                        f.error("请设置正确的电话号码及属性！");
                        return
                    }
                    if (n.patient.phoneNumberList[n.patient.phoneNumberList.length - 1].mobileType == "") {
                        f.error("请设置正确的电话号码及属性！");
                        return
                    }
                    var t = {
                        mobile: "",
                        patientId: n.patient.id,
                        attributes: "PhoneNumber",
                        mobileType: "",
                        displayOrder: n.patient.phoneNumberList.length + 1
                    };
                    n.patient.phoneNumberList.push(t)
                },
                rt = function(t) {
                    n.patient.mobileList.splice(t, 1);
                    n.patient.mobileList[n.patient.mobileList.length - 1].displayOrder = n.patient.mobileList.length
                },
                ut = function(t) {
                    n.patient.phoneNumberList.splice(t, 1);
                    n.patient.phoneNumberList[n.patient.phoneNumberList.length - 1].displayOrder = n.patient.phoneNumberList.length
                },
                ft = function() {
                    n.isEditSourceType = !c.isAllowed("patientMgmt.editSourceType");
                    d(n.patient.id).then(function() {
                        b()
                    })
                },
                et = function(n, t) {
                    var u = n.sender.wrapper,
                        i = u.next("input.mobile-number-input"),
                        r;
                    t.mobileType && i.length && (r = i.data("kendoNumericTextBox"), r.enable(!0))
                },
                ot = function(t) {
                    if (!t) return [];
                    var i = [];
                    return t.forEach(function(t, r) {
                        r == 0 && (t.attributes == "mobile" && !t.mobile && n.patient.mobile ? t.mobile == n.patient.mobile : t.attributes == "PhoneNumber" && !t.mobile && n.patient.phoneNumber && t.mobile == n.patient.phoneNumber);
                        t.mobile && i.push(t)
                    }), i
                };
            (function() {
                n.editMobile = g;
                n.editPhoneNumber = nt;
                n.addMobile = tt;
                n.addPhoneNumber = it;
                n.deleteMobile = rt;
                n.canBrowseMobileItems = ot;
                n.deletePhoneNumber = ut;
                n.onChangeMobileType = et;
                n.registerOnEditingCallBackMethod("infoBase", ft);
                n.isProfessional = a.isProfessional
            })()
        }
    }
}]);
patientModule.controller("PatientInfoContactCtrl", ["$log", "$scope", "$q", "$rootScope", "aresNotification", "$modal", "patientSvc", "conversationSvc", "aresDialog", "patientTabManager", function(n, t, i, r, u, f, e, o, s, h) {
    "use strict";
    var c = function() {
            r.isNewWxEnabled ? y() : s.warn("提示", "当前诊所未开通SCRM！")
        },
        l = function() {
            o.unBindSaasPatient(t.patientId).success(function(n) {
                if (n) {
                    var i = t.findPatientTabManagerScope();
                    i && i.patientTabManager.activeTab && i.patientTabManager.activeTab.patient && i.patientTabManager.activeTab.patient.marketCenterAccount && (i.patientTabManager.activeTab.patient.marketCenterAccount = "");
                    t.patient.marketCenterAccount = "";
                    r.$broadcast("bind-weixin", "")
                } else u.error("解绑失败")
            }).error(function(t) {
                u.error("解绑失败");
                t.name == "ScrmException" && n.log("调用SCRM解绑接口失败");
                n.log(t)
            })
        },
        a = function() {
            var i = null,
                n, r;
            if (!i)
                for (n = t.$parent, r = 0; r < 10; r++)
                    if (n == null || n.patientTabManager) {
                        i = n;
                        break
                    } else n = n.$parent;
            return i
        },
        v = function() {
            var n = i.defer();
            return e.getPatient(t.patient.id).success(function(i) {
                i.marketCenterAccount && (t.patient.marketCenterAccount = i.marketCenterAccount, r.$broadcast("bind-weixin", t.patient.marketCenterAccount), n.resolve({
                    result: !0
                }))
            }), n.promise
        },
        y = function() {
            e.generatePatientQrCode(t.patient.id).then(function(i) {
                var r, o;
                i ? (r = {
                    interval: 3e3,
                    delay: 100,
                    maxCount: 20,
                    bindWeiXin: !0,
                    queryFunc: v
                }, e.sendScrmQrCode(i).success(function() {
                    n.log("scrm2.0发送二维码到智能话机成功")
                }).error(function(t) {
                    n.log(t)
                }), o = f.open({
                    animation: !0,
                    backdrop: "static",
                    template: "<qrcode-dialog><\/qrcode-dialog>",
                    controller: "QrcodeDialogCtrl",
                    size: "sm",
                    resolve: {
                        host: function() {
                            return {
                                qrCode: i,
                                outTradeNo: 1,
                                isMarketCenter: !1,
                                queryOption: r
                            }
                        }
                    }
                }), o.result.then(function() {
                    e.getPatient(t.patient.id).success(function(n) {
                        n && n.marketCenterAccount && (h.activeTab.patient.marketCenterAccount = n.marketCenterAccount, u.success("微信绑定成功"))
                    })
                })) : u.error("该诊所未授权微信公众号")
            })
        };
    (function() {
        t.findPatientTabManagerScope = a;
        t.unBindPatientWeiXin = l;
        t.getPatientQrCode = c
    })()
}]);
patientModule.directive("patientInfoExaminationBlockView", ["$log", "$timeout", "$modal", "aresDialog", "aresNotification", "dataDicSvc", function(n, t, i, r, u, f) {
    "use strict";
    return {
        scope: !1,
        restrict: "E",
        replace: !0,
        controller: "PatientInfoEaminationBlockCtrl",
        templateUrl: "/app/patient/components/patient-info-examination-block/patient-info-examination-block-view.html",
        link: function(n, t) {
            var i, r, u, e = function(t) {
                    return n.infoExamination.isEdit ? !0 : !n.infoExamination.isEdit && n.patient && n.patient.bodycheck && n.patient.bodycheck[t] ? !0 : !1
                },
                o = function() {
                    f.medicineNowDic.load().then(function(t) {
                        n.medicineNowItems = angular.copy(t)
                    }).then(function() {
                        var t = n.patient.bodycheck && n.patient.bodycheck.medicineNow ? n.patient.bodycheck.medicineNow : "",
                            i = t != "" ? t.split(",").map(function(n) {
                                return {
                                    itemName: n
                                }
                            }) : [];
                        s(i)
                    })
                },
                s = function(r) {
                    var u = r.map(function(n) {
                        return n.itemName
                    });
                    i ? (i.setDataSource(n.medicineNowItems), i.dataSource.filter({}), i.value(u)) : i = t.find("#MedicineNow").kendoAresMultiSelect({
                        dataTextField: "itemName",
                        dataValueField: "itemName",
                        dataSource: n.medicineNowItems,
                        value: u,
                        separator: ",",
                        change: function() {
                            var t = this.value();
                            n.patient.bodycheck.medicineNow = t.length > 0 ? t.join(",") : ""
                        }
                    }).data("kendoAresMultiSelect")
                },
                h = function() {
                    f.medicineDic.load().then(function(t) {
                        n.medicineItems = angular.copy(t)
                    }).then(function() {
                        var t = n.patient.bodycheck && n.patient.bodycheck.medicine ? n.patient.bodycheck.medicine : "",
                            i = t != "" ? t.split(",").map(function(n) {
                                return {
                                    itemName: n
                                }
                            }) : [];
                        c(i)
                    })
                },
                c = function(i) {
                    var u = i.map(function(n) {
                        return n.itemName
                    });
                    r ? (r.setDataSource(n.medicineItems), r.dataSource.filter({}), r.value(u)) : r = t.find("#Medicine").kendoAresMultiSelect({
                        dataTextField: "itemName",
                        dataValueField: "itemName",
                        dataSource: n.medicineItems,
                        value: u,
                        separator: ",",
                        change: function() {
                            var t = this.value();
                            n.patient.bodycheck.medicine = t.length > 0 ? t.join(",") : ""
                        }
                    }).data("kendoAresMultiSelect")
                },
                l = function() {
                    f.diseaseDic.load().then(function(t) {
                        n.deseaseItems = angular.copy(t)
                    }).then(function() {
                        var t = n.patient.bodycheck && n.patient.bodycheck.disease ? n.patient.bodycheck.disease : "",
                            i = t != "" ? t.split(",").map(function(n) {
                                return {
                                    itemName: n
                                }
                            }) : [];
                        a(i)
                    })
                },
                a = function(i) {
                    var r = i.map(function(n) {
                        return n.itemName
                    });
                    u ? (u.setDataSource(n.deseaseItems), u.dataSource.filter({}), u.value(r)) : u = t.find("#Disease").kendoAresMultiSelect({
                        dataTextField: "itemName",
                        dataValueField: "itemName",
                        dataSource: n.deseaseItems,
                        value: r,
                        separator: ",",
                        change: function() {
                            var t = this.value();
                            n.patient.bodycheck.disease = t.length > 0 ? t.join(",") : ""
                        }
                    }).data("kendoAresMultiSelect")
                },
                v = function() {
                    n.onSaveBodycheck("infoExamination")
                },
                y = function(t) {
                    n.patient.bodycheck.isLactation = t
                },
                p = function(t) {
                    n.patient.bodycheck.isPregnant = t
                },
                w = function() {
                    o();
                    h();
                    l()
                };
            (function() {
                n.setLac = y;
                n.setPregnant = p;
                n.isBrowseShow = e;
                n.onSaveExamination = v;
                n.registerOnEditingCallBackMethod("infoExamination", w)
            })()
        }
    }
}]);
patientModule.controller("PatientInfoEaminationBlockCtrl", ["$log", "$scope", "$q", "aresNotification", function() {
    "use strict";
    (function() {})()
}]);
patientModule.directive("patientInfoExtendView", ["$log", "$timeout", "$modal", "aresDialog", "aresNotification", "permissionProvider", "officeUtil", function(n, t, i, r, u, f, e) {
    "use strict";
    return {
        scope: !1,
        restrict: "E",
        replace: !0,
        controller: "PatientInfoExtendCtrl",
        templateUrl: "/app/patient/components/patient-info-extend/patient-info-extend-view.html",
        link: function(n) {
            var t = function() {
                    var t = i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<patient-referee-detail-view><\/patient-referee-detail-view>",
                        controller: "PatientRefereeDetailCtrl",
                        size: "lg",
                        resolve: {
                            host: function() {
                                return {
                                    patient: n.patient
                                }
                            }
                        }
                    })
                },
                r = function() {
                    var t = i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<patient-tag-manage-view><\/patient-tag-manage-view>",
                        controller: "PatientTagManageCtrl",
                        windowClass: "large-dialog",
                        size: "md"
                    });
                    t.result.then(function() {
                        e.isRootGroup().then(function(t) {
                            t && (n.initPatientTagUseList(n.patient), n.updateActiveTabTags())
                        })
                    })
                },
                u = function() {
                    return f.isAllowed("managementCenter.tagCenter")
                };
            (function() {
                n.showReferee = t;
                n.editPatientTag = r;
                n.allowEditTagSetting = u
            })()
        }
    }
}]);
patientModule.controller("PatientInfoExtendCtrl", ["$log", "$scope", "$q", "aresNotification", function() {
    "use strict";
    (function() {})()
}]);
var patientInfoExtraSourceBlock;
(function() {
    "use strict";
    var n = function() {
        function n(n, t) {
            this.$timeout = n;
            this.$window = t;
            this.restrict = "E";
            this.replace = !0;
            this.templateUrl = "/app/patient/components/patient-info-extra-source-block/patient-info-extra-source-block-view.html";
            this.controller = "PatientInfoExtraSourceBlockCtrl";
            this.link = function(n) {
                var t = function() {
                        n.getDepartment().then(function() {
                            n.getPatientExtraSource().then(function() {
                                n.formatPatientExtraSource(!1)
                            })
                        })
                    },
                    i = function() {
                        n.getPatientExtraSource().then(function() {
                            n.formatPatientExtraSource(!0)
                        })
                    };
                (function() {
                    n.registerOnEditingCallBackMethod("infoPatientExtraSource", t, i);
                    n.$watch("patient", function() {
                        n.formatPatientExtraSource(!0)
                    })
                })()
            }
        }
        return n.$inject = ["$timeout", "$window"], n
    }();
    patientModule.directive("patientInfoExtraSourceBlockView", Ares.tsDirective(n))
})(patientInfoExtraSourceBlock || (patientInfoExtraSourceBlock = {}));
var patientInfoExtraSourceBlock;
(function() {
    var n = function() {
        function n(n, t, i, r, u) {
            this.$scope = n;
            this.$q = t;
            this.patientUtil = i;
            this.patientSvc = r;
            this.practiceSvc = u;
            this.PATIENT_REFERRER_MAX_COUNT = 3
        }
        return n.prototype.getDepartment = function(n) {
            var t = this,
                i = t.$q.defer();
            return t.practiceSvc.getItemTypes("referrerDepartment").success(function(r) {
                t.$scope.departments = r;
                n && n(r);
                i.resolve(!0)
            }), i.promise
        }, n.prototype.editDeapartment = function() {
            var n = this,
                t = n.patientUtil.editSysitemContent("部门");
            t.result.then(function() {
                n.getDepartment(function(t) {
                    _.each(n.$scope.patient.patientExtraSources, function(n) {
                        var i = _.find(t || [], function(t) {
                            return t == n.department
                        });
                        i || (n.department = "")
                    })
                })
            })
        }, n.prototype.getPatientExtraSource = function() {
            var n = this,
                t = n.$q.defer();
            return n.patientSvc.getPatientExtraSource(n.$scope.patient.id).then(function(i) {
                n.$scope.patient.patientExtraSources = i.data;
                t.resolve(!0)
            }), t.promise
        }, n.prototype.formatPatientExtraSource = function(n) {
            var t, i;
            if (this.$scope.patient)
                for (this.$scope.patient.patientExtraSources || (this.$scope.patient.patientExtraSources = []), t = this.PATIENT_REFERRER_MAX_COUNT - this.$scope.patient.patientExtraSources.length; t-- > 0;) i = {
                    patientId: this.$scope.patient.id
                }, n, this.$scope.patient.patientExtraSources.push(i)
        }, n.$inject = ["$scope", "$q", "patientUtil", "patientSvc", "practiceSvc"], n
    }();
    patientModule.controller("PatientInfoExtraSourceBlockCtrl", Ares.tsController(n))
})(patientInfoExtraSourceBlock || (patientInfoExtraSourceBlock = {}));
patientModule.directive("patientInfoFirstVisitBlockView", ["$log", "$timeout", "$modal", "aresDialog", "aresNotification", function() {
    "use strict";
    return {
        scope: !1,
        restrict: "E",
        replace: !0,
        controller: "PatientInfoFirstVisitBlockCtrl",
        templateUrl: "/app/patient/components/patient-info-first-visit-block/patient-info-first-visit-block-view.html",
        link: function(n) {
            var t = function() {
                if (!n.patient.firstVisit) {
                    n.patient.firstVisit = "";
                    return
                }
                var t = moment(n.patient.firstVisit, "YYYY-MM-DD", !0);
                t.isValid() || (t = moment(n.patient.firstVisit, "YYYYMMDD"), n.patient.firstVisit = t.format("YYYY-MM-DD"))
            };
            (function() {
                n.onChangeFirstVisit = t;
                n.firstVisitDatePickerOptions = {
                    max: new Date,
                    format: "yyyy-MM-dd",
                    parseFormats: ["yyyyMMdd"]
                }
            })()
        }
    }
}]);
patientModule.controller("PatientInfoFirstVisitBlockCtrl", ["$log", "$scope", "$q", "aresNotification", function() {
    "use strict";
    (function() {})()
}]);
patientModule.directive("patientInfoNewRelationView", ["$log", "$timeout", "$window", "$modal", "aresDialog", "aresNotification", "patientSvc", "appNav", function() {
    "use strict";
    return {
        scope: !1,
        restrict: "E",
        replace: !0,
        controller: "PatientInfoNewRelationCtrl",
        templateUrl: "/app/patient/components/patient-info-new-relation/patient-info-new-relation-view.html",
        link: function() {
            (function() {})()
        }
    }
}]);
patientModule.controller("PatientInfoNewRelationCtrl", ["$log", "$scope", "$q", "aresNotification", "permissionProvider", function(n, t, i, r, u) {
    "use strict";
    var f = function(n) {
        return u.isAllowed(n)
    };
    (function() {
        t.isAllowed = f
    })()
}]);
patientModule.directive("patientInfoPersonView", ["$log", "$timeout", "$modal", "aresDialog", "eventAggregator", "aresNotification", "practiceSvc", "localSvc", "patientUtil", "appNav", "loginContext", function(n, t, i, r, u, f, e, o, s, h, c) {
    "use strict";
    return {
        scope: !1,
        restrict: "E",
        replace: !0,
        controller: "PatientInfoPersonCtrl",
        templateUrl: "/app/patient/components/patient-info-person/patient-info-person-view.html",
        link: function(n, t) {
            var f = function() {
                    var t = s.editSysitemContent("国籍");
                    t.result.then(function() {
                        n.patient.nationality = "";
                        i()
                    })
                },
                o = function(i) {
                    s.editPrivateIdRule().then(function(t) {
                        var i = t[n.patient.patientType];
                        i && (i == "added" || i == "modified" || i == "deleted") && n.refreshPrivateId()
                    });
                    t.find(i.delegateTarget).blur()
                },
                h = function(n) {
                    t.find("#privateId").prop("disabled", !1);
                    t.find(n.delegateTarget).blur()
                },
                i = function() {
                    e.getNationality().success(function(i) {
                        var r = t.find("#nationality"),
                            u = n.patient,
                            f = r.kendoDropDownList({
                                dataSource: i,
                                filter: "contains",
                                optionLabel: "请选择",
                                dataTextField: "itemName",
                                dataValueField: "itemName",
                                value: n.patient.nationality,
                                select: function(t) {
                                    n.patient.nationality = this.dataItem(t.item)[this.options.dataValueField] || null
                                }
                            })
                    })
                },
                l = function() {
                    i();
                    r();
                    n.initPrivateIdEditStatus()
                },
                r = function() {
                    var t, i, r;
                    n.patient.birth ? (t = moment(n.patient.birth, "YYYY-MM-DD", !0), t.isValid() || (t = moment(n.patient.birth, "YYYYMMDD"), n.patient.birth = t.format("YYYY-MM-DD")), t.isValid() && (i = moment(Ares.today()), r = i.diff(t, "years"), n.age = r), n.isNonage = !1, n.age < 18 && (n.isNonage = !0)) : (n.age = "", n.isNonage = !1)
                },
                a = function() {
                    r();
                    n.patient.brithType = ""
                },
                v = function() {
                    if (n.patient)
                        if (n.age != "") {
                            var t = (new Date).getYear() + 1900;
                            n.patient.birth = parseInt(t) - parseInt(n.age) + "-01-01";
                            n.isNonage = !1;
                            n.patient.brithType = 2;
                            n.age < 18 && (n.isNonage = !0)
                        } else n.patient.brithType = "", n.patient.birth = "", n.isNonage = !1
                },
                y = function(t) {
                    n.patient.sex = t
                },
                p = function(t) {
                    n.patient.extension.educationLevel = t
                },
                w = function(t) {
                    n.patient.extension.marriage = t
                },
                b = function() {
                    s.changePatientType(n.patient).then(function() {
                        n.initPatient()
                    })
                },
                k = function() {
                    s.readIdentityInfo(n, !0).then(function() {
                        n.patient && n.patient.age && (n.age = n.patient.age);
                        u.publish(u.events.PatientChanged, n.patient, "readIdentityInfo")
                    })
                },
                d = function(t) {
                    n.patient.imgSrc = t.filePath;
                    n.patient.pictureId = t.id;
                    n.picture = t
                },
                g = function() {
                    n.patient.brithType = n.patient.brithType === 2 ? null : 2
                };
            (function() {
                n.birthDatePickerOptions = {
                    max: new Date,
                    format: "yyyy-MM-dd",
                    parseFormats: ["yyyyMMdd"]
                };
                n.datePickerOptions = {
                    format: "yyyy-MM-dd",
                    parseFormats: ["yyyyMMdd"]
                };
                n.onNotSureBirthClick = g;
                n.initPatientPicture = d;
                n.readIdentityInfo = k;
                n.changePatientType = b;
                n.setEducationLevel = p;
                n.setSex = y;
                n.setMarriage = w;
                n.editNationality = f;
                n.editPrivateId = h;
                n.editPrivateIdRule = o;
                n.onChangeBirth = a;
                n.onChangeAge = v;
                n.isGroup = c.isGroup;
                n.registerOnEditingCallBackMethod("infoBase", l)
            })()
        }
    }
}]);
patientModule.controller("PatientInfoPersonCtrl", ["$log", "$scope", "$q", "aresNotification", "enums", "permissionProvider", function(n, t, i, r, u, f) {
    "use strict";
    var e = [u.EducationLevel.PrimarySchool, u.EducationLevel.MiddleSchool, u.EducationLevel.HighSchool, u.EducationLevel.College, u.EducationLevel.Bachelor, u.EducationLevel.Master, u.EducationLevel.Doctor, u.EducationLevel.Other],
        o = function() {
            t.isPrivateIdEditable = f.isAllowed("patientMgmt.privateId") && t.patient.officeId == t.$root.officeId;
            t.isPrivateIdRuleEditable = f.isAllowed("patientMgmt.privateId") && (!t.infoBase.isEdit || t.patient.officeId == t.$root.officeId)
        };
    (function() {
        t.educationLevels = e;
        t.initPrivateIdEditStatus = o
    })()
}]);
patientModule.directive("patientInfoRecordActionView", ["$log", "$timeout", "$modal", "aresDialog", "aresNotification", "patientUtil", "appNav", "eventAggregator", "printUtil", function(n, t, i, r, u, f, e, o, s) {
    "use strict";
    return {
        scope: !1,
        restrict: "E",
        replace: !0,
        controller: "PatientInfoRecordActionCtrl",
        templateUrl: "/app/patient/components/patient-info-record-action/patient-info-record-action-view.html",
        link: function(n, t) {
            var r = function() {
                    var t = i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<operation-log-list-view><\/operation-log-list-view>",
                        controller: "OperationLogListCtrl",
                        size: "lg",
                        windowClass: "operation-log-dialog",
                        resolve: {
                            host: function() {
                                return {
                                    id: n.patient.id,
                                    type: "Patient"
                                }
                            }
                        }
                    })
                },
                u = function() {
                    var n = "",
                        i = t.find("#patient-barcode-batchprint");
                    n = i.length > 0 ? i.html() : t.find("#patient-barcode-print").html();
                    s.printWithIframe(n)
                },
                o = function() {
                    f.deletePatient(n.patient, !1, "PatientInfoRecordCtrl").then(function() {
                        e.reload()
                    })
                },
                h = function() {
                    f.undoArchive(n.patient).then(function(t) {
                        n.patient = t;
                        e.reload()
                    })
                };
            (function() {
                n.deletePatient = o;
                n.undoArchive = h;
                n.printBarcode = u;
                n.showPatientChangeLog = r
            })()
        }
    }
}]);
patientModule.controller("PatientInfoRecordActionCtrl", ["$log", "$scope", "$q", "aresNotification", function() {
    "use strict";
    (function() {})()
}]);
patientModule.directive("patientInfoSourceView", ["$log", "$timeout", "$modal", "aresDialog", "aresNotification", "dataDicSvc", "providerSvc", function(n, t, i, r, u, f) {
    "use strict";
    return {
        scope: !1,
        restrict: "E",
        replace: !0,
        controller: "PatientInfoSourceCtrl",
        templateUrl: "/app/patient/components/patient-info-source/patient-info-source-view.html",
        link: function(n, r) {
            var u = null,
                e = function() {
                    f.patientSourceTypeDic.load().then(function(t) {
                        var i, u;
                        n.patientSourceType = t;
                        n.patient.sourceType ? (i = _.find(t, function(t) {
                            return t.sourceName == n.patient.sourceType && t.level == 2
                        }), n.hasSourceType = i ? !0 : !1, s(t, i)) : s(t);
                        n.patient.sourceType == "员工介绍" && (u = r.find("#provider").data("kendoNameCodeFilterDropDownList"), u && u.value(n.patient.refereeId))
                    })
                },
                s = function(t, i) {
                    for (var u, s, h, e = [], f = 0; f < t.length; f++) t[f].level == 1 && t[f].isDisabled === !1 && e.push(t[f]);
                    u = {
                        sourceName: ""
                    };
                    i && (u = _.find(t, function(n) {
                        return n.id == i.parentId
                    }));
                    s = r.find("#parentSourceType");
                    h = s.kendoDropDownList({
                        dataSource: e,
                        dataTextField: "sourceName",
                        dataValueField: "sourceName",
                        optionLabel: "请选择一级来源",
                        value: u ? u.sourceName : null,
                        select: function(t) {
                            var i = this.dataItem(t.item) || null;
                            a();
                            n.patient.sourceTypeLevel1 = i.sourceName;
                            n.patient.sourceType = "";
                            n.patient.refereeName = "";
                            o();
                            l(i.id)
                        }
                    }).data("kendoDropDownList");
                    h.enable(!n.isEditSourceType);
                    u && u.sourceName ? l(u.id) : (n.hasParentSource = !1, n.patient.hasParentSource = !1)
                },
                v = function() {
                    n.providers ? h() : f.allProviderDic.loadActive().then(function(t) {
                        t.splice(0, 0, {
                            id: 0,
                            name: ""
                        });
                        n.providers = t;
                        h()
                    })
                },
                h = function() {
                    var i = r.find("#provider").kendoNameCodeFilterDropDownList({
                        dataSource: n.providers,
                        filter: "contains",
                        placeholder: "请选择推荐人",
                        dataTextField: "name",
                        dataValueField: "id",
                        value: n.patient.refereeId || null,
                        select: function(i) {
                            n.patient.refereeId = this.dataItem(i.item)[this.options.dataValueField] || 0;
                            t(function() {
                                var t = _.find(n.providers, function(t) {
                                    return t.id == n.patient.refereeId
                                });
                                n.patient.refereeName = t ? t.name : "";
                                n.patient.refereeMobileOrCode = t ? t.mobile : ""
                            })
                        }
                    }).data("kendoNameCodeFilterDropDownList");
                    i.enable(!n.isEditSourceType)
                },
                c = function(t) {
                    for (var e, u = n.patient.refereeName ? n.patient.refereeName : "", s = u != "" ? u.split(",") : [], f = [], i = 0; i < n.patientSourceType.length; i++) n.patientSourceType[i].parentId == t.id && n.patientSourceType[i].isDisabled === !1 && f.push(n.patientSourceType[i]);
                    e = r.find("#otherSourceType").kendoDropDownList({
                        dataSource: f,
                        dataTextField: "sourceName",
                        dataValueField: "sourceName",
                        optionLabel: "请选择三级来源",
                        value: u,
                        select: function(t) {
                            var i = this.dataItem(t.item) || null;
                            n.patient.refereeName = i.sourceName;
                            o()
                        }
                    }).data("kendoDropDownList");
                    e.enable(!n.isEditSourceType)
                },
                l = function(t) {
                    var u, i, f;
                    for (t ? (n.hasParentSource = !0, n.patient.hasParentSource = !0) : (n.hasParentSource = !1, n.patient.hasParentSource = !1), u = [], i = 0; i < n.patientSourceType.length; i++) n.patientSourceType[i].parentId == t && n.patientSourceType[i].isDisabled === !1 && u.push(n.patientSourceType[i]);
                    var e = r.find("#sourceType"),
                        h = n.patient,
                        s = e.kendoDropDownList({
                            dataSource: u,
                            dataTextField: "sourceName",
                            dataValueField: "sourceName",
                            optionLabel: "请选择二级来源",
                            value: n.patient.sourceType,
                            select: function(t) {
                                n.patient.sourceType = this.dataItem(t.item)[this.options.dataValueField] || null;
                                a();
                                n.patient.refereeName = null;
                                n.patient.sourceType == "朋友介绍" ? (n.enableReferee = !0, n.enableProvider = !1, n.enableOtherSourceType = !1) : n.patient.sourceType == "员工介绍" ? (n.enableProvider = !0, n.enableReferee = !1, n.enableOtherSourceType = !1) : n.patient.sourceType ? (n.enableReferee = !1, n.enableProvider = !1, n.enableOtherSourceType = !0, n.hasSourceType = !0) : (n.enableReferee = !1, n.enableProvider = !1, n.enableOtherSourceType = !1, n.hasSourceType = !1);
                                n.hasSourceType = !0;
                                o();
                                c(this.dataItem(t.item))
                            }
                        }).data("kendoDropDownList");
                    s.enable(!n.isEditSourceType);
                    f = _.find(n.patientSourceType, function(t) {
                        return t.sourceName == n.patient.sourceType && t.level == 2
                    });
                    f && c(f)
                },
                a = function() {
                    t(function() {
                        n.refereePatient = null;
                        n.patient.refereeId = 0;
                        n.patient.refereeName = null;
                        n.patient.refereeMobileOrCode = null
                    })
                },
                o = function() {
                    var n = r.find("#sourceTypeNew").data("kendoMultiFilterAutoComplete");
                    n && n.value("")
                },
                y = function() {
                    var t = i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<patient-source-type-edit-view><\/patient-source-type-edit-view>",
                        controller: "PatientSourceTypeEditCtrl",
                        windowClass: "patient-source-type-dialog"
                    });
                    t.result.then(function() {
                        n.$broadcast("patientSourceTypeChanged");
                        e()
                    })
                },
                p = function() {
                    e();
                    u = n.$watch("patient.sourceType", function() {
                        n.patient != null && (n.enableReferee = n.patient.sourceType == "朋友介绍" ? !0 : !1, n.patient.sourceType == "员工介绍" ? (n.enableProvider = !0, v()) : n.enableProvider = !1, n.enableOtherSourceType = n.patient.sourceType && n.patient.sourceType != "朋友介绍" && n.patient.sourceType != "员工介绍" ? !0 : !1)
                    })
                },
                w = function() {
                    u && u()
                },
                b = function(i) {
                    t(function() {
                        n.refereePatient = i;
                        n.patient.refereeName = i.name;
                        n.patient.refereeMobileOrCode = i.mobile;
                        n.patient.refereeId = i.id
                    })
                };
            (function() {
                n.onRefereeSelected = b;
                n.editSourceType = y;
                n.initParentSourceType = e;
                n.registerOnEditingCallBackMethod("infoBase", p, w)
            })()
        }
    }
}]);
patientModule.controller("PatientInfoSourceCtrl", ["$log", "$scope", "$q", "aresNotification", function() {
    "use strict";
    (function() {})()
}]);
patientModule.directive("patientInfoTagView", ["$log", "$timeout", "$modal", "aresDialog", "aresNotification", function(n, t, i, r, u) {
    "use strict";
    return {
        scope: !1,
        restrict: "E",
        replace: !0,
        controller: "PatientInfoTagCtrl",
        templateUrl: "/app/patient/components/patient-info-tag/patient-info-tag-view.html",
        link: function(n, t) {
            var i = function(n, i) {
                    var r = t.find(i.target);
                    r.css("border-color", n.itemValue);
                    n.selected ? r.css("color", "#fff") : r.css("color", n.itemValue)
                },
                r = function(n, i) {
                    var r = t.find(i.target);
                    n.selected ? r.css("color", "#fff") : (r.css("color", "#666a73"), r.css("border-color", "#e3e3e3"))
                },
                f = function(t) {
                    if (!t.selected) {
                        if (t.isInactive) {
                            u.error("标签已禁用，不能使用。");
                            return
                        }
                        if (n.patient.patientTagUseList.length == 9) {
                            u.error("患者标签数量最大为9个");
                            return
                        }
                        var i = t.itemValue ? Ares.getForegroundColor(t.itemValue) : Ares.getForegroundColor("#fff");
                        n.patient.patientTagUseList.push({
                            officeId: n.patient.officeId,
                            patientId: n.patient.id,
                            tagId: t.id,
                            abbreviation: t.abbreviation,
                            isHidden: t.isHidden,
                            itemValue: t.itemValue,
                            itemName: t.itemNamek,
                            textColor: i
                        });
                        t.selected = !0
                    }
                },
                e = function(t, i) {
                    var u, r;
                    if (i.stopPropagation(), t.selected && n.patient.patientTagUseList) {
                        for (u = -1, r = 0; r < n.patient.patientTagUseList.length; r++)
                            if (n.patient.patientTagUseList[r].tagId == t.id) {
                                u = r;
                                break
                            }
                        u > -1 && (n.patient.patientTagUseList.splice(u, 1), t.selected = !1)
                    }
                    Ares.sensors.track("PatientInfoTag", {
                        OperationType: "移除标签"
                    })
                };
            (function() {
                n.onMouseOver = i;
                n.onMouseLeave = r;
                n.onSelectPatientTag = f;
                n.onRemovePatientTag = e
            })()
        }
    }
}]);
patientModule.controller("PatientInfoTagCtrl", ["$log", "$scope", "$q", "aresNotification", function(n, t) {
    "use strict";
    var i = function(n) {
        var i = [];
        return t.patientTags && (i = t.patientTags.filter(function(t) {
            return t.isHidden == n && (t.selected || !t.isInactive)
        })), i
    };
    (function() {
        t.getPatientTags = i
    })()
}]);
patientModule.directive("patientTagColorSelectorView", ["$log", "$timeout", function(n, t) {
    "use strict";
    return {
        replace: !0,
        scope: {
            patientTag: "="
        },
        controller: "PatientTagColorSelectorCtrl",
        templateUrl: "/app/patient/components/patient-tag-color-selector/patient-tag-color-selector-view.html",
        link: function(n, i) {
            var f = !1,
                r, u, e = function() {
                    if (!f) {
                        var e = 12;
                        r = i.find('div.selector1 input[type="color"]').kendoColorPicker({
                            tileSize: 45,
                            columns: e,
                            palette: n.colorValues,
                            change: function(i) {
                                t(function() {
                                    var t;
                                    n.patientTag.itemValue = i.value;
                                    t = i.value ? i.value : "#fff";
                                    n.patientTag.textColor = Ares.getForegroundColor(t)
                                })
                            },
                            open: function() {
                                for (var f, i, u = $(".k-palette"), r = u.find("td.k-item"), t = 0; t < n.patientTagColors.length; t++) $(r[t]).addClass("color-cell").html(n.patientTagColors[t].name), $(r[t]).css({
                                    "text-align": "center",
                                    "font-size": "xx-small",
                                    color: "black"
                                });
                                if (f = n.patientTagColors.length, i = $(r[f]), !i.hasClass("non-color") && (i.addClass("non-color"), i.css("text-align", "center"), n.colorValues.length != n.patientTagColors.length)) {
                                    var o = Math.floor((n.patientTagColors.length + e - 1) / e - 1),
                                        s = u.find("tr:eq(" + o + ")"),
                                        h = '<tr><td style="text-align:center" colspan="' + e + '">-----自定义颜色-----<\/td><\/tr>';
                                    $(h).insertAfter(s)
                                }
                            }
                        }).data("kendoColorPicker");
                        u = i.find('div.selector2 input[type="color"]').kendoColorPicker({
                            buttons: !0,
                            open: function() {
                                this.value(n.patientTag.itemValue)
                            },
                            change: function(i) {
                                t(function() {
                                    var t;
                                    n.patientTag.itemValue = i.value;
                                    t = i.value ? i.value : "#fff";
                                    n.patientTag.textColor = Ares.getForegroundColor(t)
                                })
                            }
                        }).data("kendoColorPicker");
                        i.find("div.selector1").css("display", "inline-block");
                        i.find("div.selector2").css("display", "inline-block");
                        f = !0
                    }
                },
                o = function() {
                    n.patientTag.isEditing && i.find("div.selector1 span.k-selected-color").click()
                },
                s = function() {
                    n.patientTag.isEditing && i.find("div.selector2 span.k-selected-color").click()
                };
            (function() {
                n.selectColor1 = o;
                n.selectColor2 = s;
                n.$watch("patientTag.isEditing", function() {
                    n.patientTag.isEditing ? e() : (r && (kendo.destroy(r.element), r = null), u && (kendo.destroy(u.element), u = null), f = !1)
                })
            })()
        }
    }
}]);
patientModule.controller("PatientTagColorSelectorCtrl", ["$log", "$scope", function(n, t) {
    "use strict";
    var i = function(n, t) {
            this.name = n;
            this.value = t
        },
        r = [new i("辣椒红", "#941100"), new i("深褐色", "#945300"), new i("芦笋绿", "#929000"), new i("草绿色", "#4e9000"), new i("三叶草绿", "#008f00"), new i("苔藓绿", "#009051"), new i("深青色", "#009192"), new i("海水蓝", "#005493"), new i("夜空蓝", "#021893"), new i("茄紫色", "#531b93"), new i("深紫色", "#942092"), new i("栗色", "#941651"), new i("樱桃红", "#ff2500"), new i("橘红色", "#ff9400"), new i("柠檬黄", "#fffb00"), new i("浅绿色", "#8efa00"), new i("春天新绿", "#00f900"), new i("亮绿色", "#00f992"), new i("蓝绿色", "#00fdff"), new i("浅蓝色", "#0097ff"), new i("蓝莓色", "#0433ff"), new i("葡萄紫", "#9537ff"), new i("洋红", "#ff40ff"), new i("草莓红", "#ff3092"), new i("橙红色", "#ff7e78"), new i("橘黄色", "#ffd479"), new i("香蕉黄", "#fffc79"), new i("嫩绿色", "#d4fb78"), new i("青绿色", "#72fa79"), new i("浅蓝绿色", "#74fdd7"), new i("天空蓝", "#76d5ff"), new i("淡紫色", "#7980ff"), new i("浅紫色", "#d883ff"), new i("桃红色", "#ff85ff"), new i("粉红色", "#ff89d7"), new i("无", "#ffffff"), ],
        u = _.map(r, function(n) {
            return n.value
        });
    (function() {
        t.patientTagColors = r;
        t.colorValues = u
    })()
}]);
patientModule.directive("patientTagsManageBlockView", ["$log", "$timeout", "$window", "$q", "aresNotification", "aresDialog", function(n, t, i, r, u, f) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/components/patient-tags-manage-block/patient-tags-manage-block-view.html",
        controller: "PatientTagsManageBlockCtrl",
        link: function(n, i) {
            var o = function() {
                    var t = null;
                    t = n.allEnabled ? "确定启用所有标签？" : "确定禁用所有标签？";
                    f.confirm("提醒", t).then(function() {
                        n.patientTags.forEach(function(t) {
                            var i = [];
                            t.isInactive == n.allEnabled && (t.isInactive = !t.isInactive, t.id && i.push(n.updatePatientTag(t)));
                            i.length > 0 && r.all(i).then(function() {}, function() {
                                n.allEnabled = !n.allEnabled
                            })
                        })
                    }, function() {
                        n.allEnabled = !n.allEnabled
                    })
                },
                e = function(n, t) {
                    var i = $(n.target).parents("tr");
                    t ? (i.find(".ares-show").hide(), i.find(".ares-edit").show()) : (i.find(".ares-show").show(), i.find(".ares-edit").hide())
                },
                s = function(t, i) {
                    if (n.isExistUnsaveChanges()) {
                        u.error("请先保存患者标签！");
                        return
                    }
                    i.isEditing = !0;
                    i.copy = angular.copy(i);
                    e(t, !0)
                },
                h = function(t, i) {
                    i.id ? (i.isEditing = !1, e(t, !1), i.copy = null) : n.patientTags.splice(n.patientTags.length - 1, 1)
                },
                c = function(t, i) {
                    y(i.copy) && (i.id ? n.updatePatientTag(i.copy).then(function() {
                        angular.extend(i, i.copy);
                        i.isEditing = !1;
                        e(t, !1)
                    }, function() {}) : n.savePatientTag(i.copy).then(function() {
                        angular.extend(i, i.copy);
                        i.isEditing = !1;
                        e(t, !1)
                    }))
                },
                l = function(n) {
                    n.isHidden = n.isHiddenStr == "隐性" ? !0 : !1
                },
                a = function(t) {
                    t.isInactive = !t.isInactive;
                    n.updatePatientTag(t).then(function() {
                        n.allEnabled = t.isInactive ? !1 : n.isAllActive()
                    }, function() {
                        t.isInactive = !t.isInactive
                    })
                },
                v = function(n) {
                    n.copy.abbreviation = n.copy.itemName ? n.copy.itemName.substr(0, 1) : ""
                },
                y = function(n) {
                    return (n.itemName = n.itemName.trim(), n.abbreviation = n.abbreviation.trim(), !n.itemName) ? (u.error("标签名称不能为空！"), !1) : n.abbreviation ? !0 : (u.error("标签缩写不能为空！"), !1)
                },
                p = function() {
                    if (n.isExistUnsaveChanges()) {
                        u.error("请先保存患者标签！");
                        return
                    }
                    n.createPatientTag();
                    t(function() {
                        var n = i.find("table > tbody tr:last");
                        n.find(".ares-show").hide();
                        n.find(".ares-edit").show();
                        n.find("input:eq(0)").focus()
                    })
                },
                w = function() {
                    var r = !1,
                        t, i;
                    if (n.patientTags)
                        for (t = 0; t < n.patientTags.length; t++)
                            if (i = n.patientTags[t], i.isEditing || i.id == 0) {
                                r = !0;
                                break
                            }
                    return r
                };
            (function() {
                n.enableOrDisableAll = o;
                n.onEditTag = s;
                n.onCancelEdit = h;
                n.onSaveTag = c;
                n.onHiddenChanged = l;
                n.onEnableOrDisableClick = a;
                n.onTagNameChanged = v;
                n.onAddPatientTag = p;
                n.isExistUnsaveChanges = w
            })()
        }
    }
}]);
patientModule.controller("PatientTagsManageBlockCtrl", ["$log", "$timeout", "$scope", "$modal", "$q", "aresDialog", "aresNotification", "practiceSvc", "transactionCodeSvc", "dataDicSvc", function(n, t, i, r, u, f, e, o, s, h) {
    "use strict";
    var l = function() {
            o.listPatientTags().success(function(n) {
                n && (n.forEach(function(n) {
                    n.isHiddenStr = n.isHidden ? "隐性" : "显性";
                    n.isEditing = !1;
                    n.textColor = n.itemValue ? Ares.getForegroundColor(n.itemValue) : Ares.getForegroundColor("#fff")
                }), i.patientTags = n, i.allEnabled = c())
            })
        },
        c = function() {
            if (i.patientTags) {
                var n = i.patientTags.find(function(n) {
                    return n.isInactive
                });
                return n ? !1 : !0
            }
            return !1
        },
        a = function(n) {
            var t = u.defer();
            return o.createPatientTag(n).success(function(i) {
                n.id = i.id;
                h.patientTagDic.refresh();
                t.resolve()
            }).error(function(n) {
                n.name === "TagItemNameNotUniqueException" ? e.error("该名称已经存在！") : e.error("标签保存失败！");
                t.reject()
            }), t.promise
        },
        v = function(n) {
            var t = u.defer();
            return o.updatePatientTag(n).success(function() {
                h.patientTagDic.refresh();
                t.resolve()
            }).error(function(n) {
                n.name === "TagItemNameNotUniqueException" ? e.error("该名称已经存在！") : e.error("标签更新失败！");
                t.reject()
            }), t.promise
        },
        y = function() {
            var n = {
                itemName: "",
                itemType: "患者标签",
                itemValue: "#f6a623",
                abbreviation: "",
                displayOrder: null,
                id: 0,
                isDefault: !1,
                isEditing: !0,
                isHidden: !1,
                isHiddenStr: "显性",
                isInactive: !1
            };
            n.copy = angular.copy(n);
            i.patientTags.push(n)
        };
    (function() {
        i.updatePatientTag = v;
        i.isAllActive = c;
        i.createPatientTag = y;
        i.savePatientTag = a;
        l()
    })()
}]);
patientModule.directive("pictureHostEditView", ["$log", "$timeout", "$window", "$q", "aresNotification", "aresDialog", function(n, t) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/components/picture-host-edit/picture-host-edit-view.html",
        scope: {
            targetType: "@",
            pictureList: "="
        },
        link: function(n, i) {
            var r, u = function() {
                    var u = i.find("#pictureTag");
                    r = u.kendoDropDownList({
                        dataSource: [{
                            itemName: "U/L图"
                        }, {
                            itemName: "牙模"
                        }, {
                            itemName: "比色图"
                        }, {
                            itemName: "其他"
                        }],
                        dataTextField: "itemName",
                        dataValueField: "itemName",
                        optionLabel: "请选择",
                        select: function(i) {
                            var r = this.dataItem(i.item)[this.options.dataValueField] || null;
                            r && (n.tags = r, t(function() {
                                angular.element(".ares-picture-container button").click()
                            }))
                        }
                    })
                },
                f = function(t) {
                    var i = {
                            tags: n.tags,
                            pictureName: t.name,
                            pictureId: t.id,
                            filePath: encodeURIComponent(t.filePath),
                            targetType: n.targetType
                        },
                        r = _.find(n.pictureList, function(t, r) {
                            var u = !1;
                            return t.tags == i.tags && (n.pictureList[r] = i, u = !0), u
                        });
                    r || n.pictureList.push(i)
                },
                e = function(t) {
                    n.pictureList.splice(t, 1)
                };
            (function() {
                n.updatePicture = f;
                n.removeImg = e;
                n.pictureList = n.pictureList || [];
                u()
            })()
        }
    }
}]);
patientModule.directive("productAutoCompleteSelectorView", ["$window", "$q", "$timeout", "dentalLabSvc", "enums", function(n, t, i, r) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/components/product-auto-complete-selector/product-auto-complete-selector-view.html",
        scope: {
            onSelect: "&",
            dealerIds: "=?"
        },
        link: function(u, f) {
            var o = f.find("input"),
                s, h = function() {
                    var f = angular.element(n).height() - o.offset().top - 300,
                        t = '<div class="dropdown-select-head" style="background: #00A6C9; color: #FFF;"><span style="display: inline-block;width:223px;margin-left:10px">项目名称<\/span><span style="display: inline-block;width:190px;margin-left:10px">产地<\/span><span style="display: inline-block;width:190px;margin-left:10px;text-align:center;">技加工厂<\/span>',
                        r;
                    t += "<\/div>";
                    r = '<span class="dropdown-select-text" style="width:223px;margin-left:10px" title="#: data.nameSpec #">#: data.nameSpec #<\/span><span class="dropdown-select-text" style="width:190px;margin-left:10px">#: data.factoryLocation ==null ? "" :data.factoryLocation #<\/span><span class="dropdown-select-text" style="width:190px;margin-left:10px;text-align:center;">#: data.dealerName ==null ? "" : data.dealerName #<\/span>';
                    s = o.kendoAutoComplete({
                        filter: "contains",
                        placeholder: "项目名称/拼首码",
                        minLength: 1,
                        dataTextField: "name",
                        dataValueField: "id",
                        headerTemplate: t,
                        template: r,
                        dataSource: {
                            type: "odata",
                            serverFiltering: !0,
                            transport: {
                                read: function(n) {
                                    var t = n.data.filter !== undefined ? n.data.filter.filters[0] : undefined,
                                        i = t ? t.value : "";
                                    _.defer(function() {
                                        v(i).then(function(t) {
                                            n.success(t)
                                        })
                                    })
                                }
                            }
                        },
                        height: f,
                        select: function(n) {
                            u.selectedIndex = n.item.index()
                        },
                        change: function(n) {
                            var t = null,
                                i = this.value();
                            this.selectedIndex = u.selectedIndex >= 0 ? u.selectedIndex : -2;
                            this.selectedIndex >= 0 && (t = this.dataItem(this.selectedIndex), u.selectedIndex = -2);
                            c(t, n);
                            this.value("")
                        },
                        dataBound: function(n) {
                            i(function() {
                                var t = n.sender.popup.element,
                                    i = t.find(".dropdown-select-head").outerHeight() + t.find(".k-list").height();
                                t.height(i)
                            }, 0, !1)
                        }
                    }).data("kendoAutoComplete")
                },
                c = function(n, t) {
                    if (n) u.onSelect({
                        selectedProduct: n,
                        event: t
                    })
                },
                l = function() {
                    s.search("")
                },
                a = function(n) {
                    var i = t.defer(),
                        f = {
                            pageIndex: 1,
                            pageSize: 50,
                            searchText: n,
                            hasEnableSales: !0,
                            dealerIds: u.dealerIds
                        };
                    return r.searchProduct(f).success(function(n) {
                        var t = n.items;
                        y(t);
                        i.resolve(t)
                    }), i.promise
                },
                e, v = function(n) {
                    var r = t.defer();
                    return e && (i.cancel(e), e = null), e = i(function() {
                        return a(n).then(function(n) {
                            u.products = n;
                            e = null;
                            r.resolve(n)
                        })
                    }, 300), r.promise
                },
                y = function(n) {
                    _.each(n, function(n) {
                        n.nameSpec = n.name + "-" + n.specification
                    })
                };
            (function() {
                h();
                u.focusAutoComplete = l
            })()
        }
    }
}]);
patientModule.directive("productSupplierDropdownView", ["$timeout", "$compile", "$window", "$document", "$q", "toFormatPriceFilter", "enums", "dentalLabSvc", function(n, t, i, r, u, f, e, o) {
    "use strict";
    return {
        restrict: "E",
        scope: {
            dentalLabOrderItem: "=",
            productItem: "=",
            onSelect: "&"
        },
        templateUrl: "/app/patient/components/product-supplier-dropdown/product-supplier-dropdown-view.html",
        link: function(t, r) {
            t.mode || (t.mode = "input");
            var e, s = r.find(".product-supplier-dropdown-anchor"),
                h = function() {
                    n(function() {
                        var n = e.find(".product-supplier-popover-body-wrapper");
                        n.data("mCustomScrollbarIndex") ? n.mCustomScrollbar("update") : n.mCustomScrollbar({
                            scrollButtons: {
                                enable: !1
                            },
                            autoHideScrollbar: !0,
                            scrollInertia: 150,
                            advanced: {
                                updateOnContentResize: !0
                            }
                        });
                        e.find("product-supplier-popover-search-input input").focus()
                    }, 0, !1)
                },
                c = function() {
                    var u, n, r;
                    (e = s.data("bs.popover").$tip, e.find(".arrow").remove(), u = 0, n = t.currentProductSuppliers && t.currentProductSuppliers.length, n) && (n = n > 6 ? 6 : n, r = n * 28 + 32 + 32, angular.element(i).height() - s.offset().top - 32 < r && (u = -32 - r), e.css({
                        padding: 0,
                        border: 0,
                        marginLeft: "-130px",
                        marginTop: u + "px",
                        background: "transparent",
                        boxShadow: "none",
                        height: r + "px",
                        minHeight: "unset"
                    }), h())
                },
                l = function() {
                    t.editSupplierSearch.text = "";
                    a(t.productItem.productId).then(function(i) {
                        _.each(i, function(n) {
                            n.priceStr = n.price > 0 ? f(n.price) : "无"
                        });
                        t.currentProductSuppliers = i;
                        t.filteredProductSuppliers = _.clone(t.currentProductSuppliers);
                        n(function() {
                            s.popover("show")
                        })
                    })
                },
                a = function(n) {
                    var t = u.defer(),
                        i = {
                            productIds: [n]
                        };
                    return o.searchDealers(i).then(function(n) {
                        t.resolve(n.data)
                    }), t.promise
                },
                v = function(n) {
                    if (angular.isDefined(t.onSelect)) t.onSelect({
                        dealer: n
                    });
                    s.popover("hide")
                },
                y = function() {
                    t.filteredProductSuppliers = _.filter(t.currentProductSuppliers, function(n) {
                        return n.dealerName.indexOf(t.editSupplierSearch.text) > -1
                    });
                    h()
                };
            (function() {
                t.editSupplierSearch = {
                    text: ""
                };
                t.showSupplierPopover = l;
                t.onShowSupplierPopover = c;
                t.onDealerSelectedWrapper = v;
                t.onEditSupplierSearchTextChange = y
            })()
        }
    }
}]);
patientModule.controller("DiseaseItemSelectionController", ["$log", "$scope", "$modalInstance", function(n, t, i) {
    "use strict";
    t.cancel = function() {
        i.dismiss("cancel")
    };
    t.ok = function() {
        t.currentDiseaseItem && i.close(t.currentDiseaseItem)
    };
    t.onDoubleClickDiseaseItemFullTree = function(n) {
        var r = this.diseaseItemFullTree.dataItem(n.target);
        r.parentNode() && (t.currentDiseaseItem = r, i.close(r))
    };
    t.onDiseaseItemFullTreeChange = function(n) {
        t.currentDiseaseItem = n
    }
}]);
patientModule.controller("DisposalDialogCtrl", ["$log", "$scope", "$modalInstance", "$location", "$http", "$state", "appNav", "enums", "patientSvc", "practiceSvc", "aresDialog", "loginContext", "dataDicSvc", function(n, t, i, r, u, f, e, o, s, h) {
    "use strict";
    t.disposalItemList = {};
    var c = function() {
            h.getDiagnoseItemList().success(function(n) {
                t.disposalItemList = n
            })
        },
        l = function(n) {
            i.close(n)
        };
    t.cancel = function() {
        i.close(null)
    };
    c();
    t.save2 = l
}]);
patientModule.controller("GroupPatientConsultRecordCtrl", ["$log", "$scope", "$filter", "$sce", "$modal", "onlineConsultSvc", "enums", "patientUtil", "loginContext", "aresSlidePanel", function(n, t, i, r, u, f, e, o, s, h) {
    "use strict";
    var l = i("toOnlineConsultStateStr"),
        a = function(n) {
            var i, r;
            return t.isAllLevel ? !0 : t.isPersonalLevel ? (i = s.userId, i == n.recordCreatedUser ? !0 : !1) : (r = s.department, r == n.createdUserDepartment ? !0 : !1)
        },
        c = function() {
            var n = t.isPersonalLevel ? !1 : !0;
            f.getPatientOnlineConsults(t.patientId, n).success(function(n) {
                angular.forEach(n, function(n) {
                    n.stateStr = l(n.state);
                    n.isOnline = n.channel == e.AppointmentConsultChannel.Online;
                    n.canEdit = n.isOnline && a(n)
                });
                t.consultList = n
            })
        },
        v = function() {
            var n = h.open("<online-consult-detail-edit-view><\/online-consult-detail-edit-view>", "OnlineConsultDetailEditCtrl", {
                host: function() {
                    return {
                        title: "新建咨询",
                        patientId: t.patientId
                    }
                }
            }, t);
            n.result.then(function() {
                c()
            })
        },
        y = function(n) {
            var i = h.open("<online-consult-detail-edit-view><\/online-consult-detail-edit-view>", "OnlineConsultDetailEditCtrl", {
                host: function() {
                    return {
                        title: "编辑咨询",
                        consultId: n,
                        patientId: t.patientId
                    }
                }
            }, t);
            i.result.then(function() {
                c()
            })
        },
        p = function() {
            t.patientPermissionLevel = o.getPatientPermissionLevel();
            t.isAllLevel = t.patientPermissionLevel == e.PatientPermissionLevel.All;
            t.isPersonalLevel = t.patientPermissionLevel == e.PatientPermissionLevel.Personal;
            t.isDepartmentLevel = t.patientPermissionLevel == e.PatientPermissionLevel.Department
        };
    (function() {
        p();
        t.createConsult = v;
        t.editConsult = y;
        c()
    })()
}]);
patientModule.controller("InstrumentPackageUseRecordCtrl", ["$log", "$scope", "$q", "$modal", "$timeout", "cssdSvc", "aresConfirmDialog", "aresNotification", function(n, t, i, r, u, f, e, o) {
    "use strict";
    var s = function(n) {
            _.each(n, function(n) {
                n.date = moment(n.usingTime).format("L");
                n.time = moment(n.usingTime).format("HH:mm:ss");
                n.expiredDate = moment(n.expiredDate).format("L");
                n.sterTime && (n.sterTime = moment(n.sterTime).format("YYYY-MM-DD HH:mm:ss"))
            });
            var t = _.groupBy(n, "date"),
                i = [],
                r = _.keys(t);
            return _.each(r, function(n) {
                var r = {
                    date: n,
                    week: moment(n).format("dddd").replace("星期", "周"),
                    detail: t[n]
                };
                i.push(r)
            }), i
        },
        h = function(n) {
            f.getPatientPackageInstaneUseLog(n).success(function(n) {
                t.packageInstanceUseList = s(n.items)
            })
        },
        c = function(n) {
            e.warn({
                message: "您确认撤消此器械包的使用么?",
                onConfirm: function() {
                    f.revokeCssdPackageInstanceUseLog(n).success(function() {
                        o.success("撤销成功!");
                        t.searchLog()
                    })
                },
                onCancel: function() {}
            })
        };
    (function() {
        t.getPackageInstanceUseList = h;
        t.revokePackageInstanceUseLog = c
    })()
}]);
patientModule.controller("PatientAdminRecordCtrl", ["$log", "$scope", "$q", "$modal", "$timeout", "$filter", "appNav", "eventAggregator", "enums", "constants", "patientSvc", "dataDicSvc", "membershipSvc", "aresDialog", "loginContext", "providerSvc", "patientUtil", "reportSvc", "practiceSvc", "aresNotification", "conversationSvc", "patientTabManager", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b, k, d, g, nt) {
    "use strict";
    var tt = 0,
        lt = function(n) {
            t.patient.sex = n
        },
        at = function() {
            t.isEditMode = !0;
            t.isCreateMode = !1
        },
        vt = function() {
            t.isEditMode = !1;
            t.isCreateMode = !1;
            t.$parent.switchState("patient.record")
        },
        yt = function(n) {
            u(function() {
                t.refereePatient = n;
                t.patient.refereeName = n.name;
                t.patient.refereeId = n.id;
                t.patient.refereeMobileOrCode = n.mobile
            })
        },
        pt = function() {
            t.patient.refereeName && t.refereePatient && t.refereePatient.name == t.patient.refereeName || ft()
        },
        ft = function() {
            u(function() {
                t.refereePatient = null;
                t.patient.refereeId = 0;
                t.patient.refereeName = "";
                t.patient.refereeMobileOrCode = ""
            })
        },
        wt = function() {
            var u, i, r, n;
            for (t.patient.mobile = t.mobileList[0].mobile, t.patient.phoneNumber = t.phoneNumberList[0].mobile, u = /^(13[0-9\*]{9})|(19[0-9\*]{9})|(18[0-9\*]{9})|(14[0-9\*]{9})|(17[0-9\*]{9})|(15[0-9\*]{9})|(166[0-9\*]{8})$/, n = 0; n < t.mobileList.length; n++) {
                if (t.mobileList[n].mobile != "" && (!u.test(t.mobileList[n].mobile) || t.mobileList[n].mobile.length != 11)) {
                    t.showErrorNotification("请填写正确的手机号码" + (n + 1) + "！");
                    return
                }
                if (n == 0) {
                    if (t.requiredMobile) {
                        if (t.mobileList[n].mobile == "") {
                            t.showErrorNotification("请填写号码" + (n + 1) + "的手机号码！");
                            return
                        }
                    } else t.mobileList[n].mobile == "" && n != 0 && t.mobileList.splice(n, 1);
                    if (t.mobileList[n].mobile != "" && (t.mobileList[n].mobileType == "" || t.mobileList[n].mobileType == null)) {
                        t.showErrorNotification("请选择号码" + (n + 1) + "的手机号码属性！");
                        return
                    }
                } else {
                    if (t.mobileList[n].mobile != "" && (t.mobileList[n].mobileType == "" || t.mobileList[n].mobileType == null)) {
                        t.showErrorNotification("请选择号码" + (n + 1) + "的手机号码属性！");
                        return
                    }
                    if (t.mobileList[n - 1].mobile == t.mobileList[n].mobile && t.mobileList[n - 1].mobile != "" && t.mobileList[n].mobile != "" && t.mobileList[n - 1].mobileType == "本人" && t.mobileList[n].mobileType == "本人") {
                        t.showErrorNotification("本人手机必须唯一");
                        return
                    }
                    if (t.requiredMobile) {
                        if (t.mobileList[n].mobile == "") {
                            t.showErrorNotification("请填写号码" + (n + 1) + "的手机号码或者删除号码" + (n + 1) + "！");
                            return
                        }
                    } else t.mobileList[n].mobile == "" && n != 0 && t.mobileList.splice(n, 1)
                }
            }
            for (n = 0; n < t.phoneNumberList.length; n++) {
                if (t.phoneNumberList[n].mobile != "" && (t.phoneNumberList[n].mobileType == "" || t.phoneNumberList[n].mobileType == null)) {
                    t.showErrorNotification("请选择号码" + (n + 1) + "的电话号码属性！");
                    return
                }
                if (t.requiredPhoneNumber) {
                    if (t.phoneNumberList[n].mobile == "") {
                        if (n == 0) {
                            t.showErrorNotification("请填写号码" + (n + 1) + "的电话号码！");
                            return
                        }
                        t.showErrorNotification("请填写号码" + (n + 1) + "的电话号码或者删除号码" + (n + 1) + "！");
                        return
                    }
                } else t.phoneNumberList[n].mobile == "" && n != 0 && t.phoneNumberList.splice(n, 1)
            }
            for (t.telePhoneNumber = angular.copy(t.mobileList), n = 0; n < t.phoneNumberList.length; n++) t.telePhoneNumber.push(t.phoneNumberList[n]);
            if (t.patient.tag) {
                for (t.patientTabManager = nt, i = t.patient.tag, r = [], n = 0; n < i.length; n++) r.push({
                    tagId: i[n]
                });
                t.patient.patientTagUseList = r
            } else t.patient.patientTagUseList = null;
            if (bt(t.patient.tag), t.patient.pictureId = t.picture.id, t.patient.privateId == null || t.patient.privateId == "") {
                v.warn("提示", "病历号不能为空！");
                return
            }
            t.patient.refereeName || ft();
            c.checkTelePhoneNumber(t.telePhoneNumber).success(function(n) {
                if (n) {
                    t.patient.telephoneNumberList = t.telePhoneNumber;
                    c.updatePatient(t.patient).success(function(n) {
                        if (!n) {
                            v.warn("提示", "身份证已存在！");
                            return
                        }
                        t.patient = n;
                        l.otherSourceTypeDic.refresh();
                        t.$parent.switchState("patient.record")
                    }).error(function(n) {
                        n.name === "PrivateIdNotUniqueException" && v.warn("提示", "病历号已经被使用！")
                    });
                    var i = !1;
                    c.getBodyCheck(t.patientId).success(function(n) {
                        n != null ? (i = !1, t.bodycheck.id = n.id, et(i)) : (i = !0, et(i))
                    })
                } else t.showErrorNotification("本人手机必须唯一")
            })
        },
        bt = function(n) {
            if (nt && nt.activeTab && nt.activeTab.patient) {
                var i = [];
                angular.forEach(n, function(n) {
                    var r = _.find(t.patientTag, {
                        id: n
                    });
                    r && (r.title = r.isHidden ? "" : r.itemName, r.firstLetter = r.abbreviation ? r.abbreviation : r.itemName.substring(0, 1), i.push(r))
                });
                nt.activeTab.patient.tags = i
            }
        },
        et = function(n) {
            n ? (t.bodycheck.patientId = tt, c.createBodyCheck(t.bodycheck).success(function(n) {
                t.patient.medicine = n.medicine;
                rt(t.patientId);
                l.medicineDic.refresh();
                l.medicineNowDic.refresh();
                l.diseaseDic.refresh();
                l.systemsettingDic.clearCache();
                ot(t.patient)
            })) : (t.bodycheck.patientId = tt, c.updateBodyCheck(t.bodycheck).success(function(n) {
                t.bodycheck = n;
                t.patient.medicine = t.bodycheck.medicine;
                rt(t.patientId);
                l.medicineDic.refresh();
                l.medicineNowDic.refresh();
                l.diseaseDic.refresh();
                l.systemsettingDic.clearCache();
                ot(t.patient)
            }))
        },
        ot = function(n) {
            o.publish(o.events.PatientChanged, n, "PatientRecordCtrl")
        },
        st = function() {
            l.patientTagDic.load().then(function(n) {
                n = _.filter(n, function(n) {
                    return n.isInactive == !1
                });
                t.patientTag = n;
                c.getPatient(t.patientId).success(function(i) {
                    var f, e, r, u, h;
                    if (i.patientTagUseList) {
                        for (f = [], e = [], r = 0; r < i.patientTagUseList.length; r++) {
                            if (t.patientTag)
                                for (u = 0; u < t.patientTag.length; u++) i.patientTagUseList[r].tagId == t.patientTag[u].id && (h = _.any(n, function(n) {
                                    return n.id == t.patientTag[u].id && n.isInactive == !1
                                }), h && f.push(t.patientTag[u]));
                            e[r] = i.patientTagUseList[r].tagId
                        }
                        i.tag = e;
                        angular.forEach(f, function(n) {
                            !n.abbreviation && n.itemName && (n.abbreviation = n.itemName.substring(0, 1))
                        });
                        i.tagList = _.filter(f, function(n) {
                            return n.isHidden == !1
                        });
                        i.hidenTagList = _.filter(f, function(n) {
                            return n.isHidden == !0
                        })
                    }
                    t.patient = i;
                    t.patient.refereeId > 0 && (t.refereePatient = {
                        id: t.patient.refereeId,
                        name: t.patient.refereeName,
                        mobile: t.patient.refereeMobileOrCode
                    });
                    t.patient.sourceType == s.SourceType.Friend ? (t.enableReferee = !0, t.enableProvider = !1, t.enableOtherSourceType = !1) : t.patient.sourceType == s.SourceType.Provider ? (t.enableProvider = !0, t.enableReferee = !1, t.enableOtherSourceType = !1) : t.patient.sourceType ? (t.enableReferee = !1, t.enableProvider = !1, t.enableOtherSourceType = !0) : (t.enableReferee = !1, t.enableProvider = !1, t.enableOtherSourceType = !1);
                    c.getRefereeCountByPatientId(t.patientId).success(function(n) {
                        t.refereeCount = n;
                        o.publish(o.events.PatientLoaded, i, "PatientRecordCtrl");
                        i.doctorId != null && p.getName(i.doctorId).then(function(n) {
                            n && (t.patient.doctorName = n)
                        });
                        i.dutyDoctorId != null && p.getName(i.dutyDoctorId).then(function(n) {
                            t.patient.dutyDoctorName = n
                        });
                        i.consultantId != null && p.getName(i.consultantId).then(function(n) {
                            t.patient.consultantName = n || ""
                        });
                        i.attendantId != null && l.attendantDic.load().then(function(n) {
                            var r = _.find(n, function(n) {
                                return n.id == i.attendantId
                            });
                            t.patient.attendantName = r ? r.name : ""
                        });
                        i.id && (tt = i.id, rt(i.id), it(i.id), kt(i.id));
                        i.membershipId ? dt(i.membershipId) : gt(i.id);
                        i.pictureId != 0 && ht(i.pictureId);
                        fi()
                    })
                })
            })
        },
        ht = function(n) {
            c.getPictureById(n).success(function(n) {
                t.picture = n
            })
        },
        it = function(n) {
            b.GetPatientRelation(n).success(function(n) {
                for (var i = 0; i < n.length; ++i) n[i].sex = f("toSexString")(n[i].sex);
                t.patientRelation = n
            }).error(function() {})
        },
        rt = function(n) {
            c.getBodyCheck(n).success(function(n) {
                var r, u, i;
                if (n) {
                    if (n.isPregnant = n.isPregnant == !0 ? "是" : "否", n.isLactation = n.isLactation == !0 ? "是" : "否", l.medicineDic.refresh(), n.medicine) {
                        for (r = n.medicine.split(","), u = [], i = 0; i < r.length; i++) u[i] = r[i];
                        l.medicineDic.load().then(function(i) {
                            for (var u = _.map(i, function(n) {
                                    return n.itemName
                                }), r = 0; r < n.medicine.length; r++) _.indexOf(u, n.medicine[r]) == -1 && n.medicine[r] != "" && i.push({
                                itemName: n.medicine[r]
                            });
                            t.medicineLists = i
                        })
                    } else l.medicineDic.load().then(function(n) {
                        t.medicineLists = n
                    });
                    t.bodycheck = n
                } else l.medicineDic.load().then(function(n) {
                    t.medicineLists = n
                }), t.bodycheck = {}
            })
        },
        kt = function(n) {
            c.getMobileByPatientId(n).success(function(i) {
                if (i.length > 0) t.mobileList = i;
                else {
                    var r = {
                        mobile: "",
                        patientId: n,
                        attributes: "mobile",
                        displayOrder: 1,
                        mobileType: "本人"
                    };
                    t.mobileList.push(r)
                }
            });
            c.getPhoneNumberByPatientId(n).success(function(i) {
                if (i.length > 0) t.phoneNumberList = i;
                else {
                    var r = {
                        mobile: "",
                        patientId: n,
                        attributes: "PhoneNumber",
                        displayOrder: 1,
                        mobileType: "家"
                    };
                    t.phoneNumberList.push(r)
                }
            })
        },
        dt = function(n) {
            a.getMembership(n).success(function(n) {
                t.isShareMember = !1;
                ut(n)
            })
        },
        gt = function(n) {
            c.getMembership(n).success(function(n) {
                n && (t.isShareMember = !0, ut(n))
            })
        },
        ut = function(n) {
            if (n) {
                var i = l.membershipTypeDic.getItemSync(n.membershipTypeId);
                n.membershipTypeName = i.name;
                t.membership = n;
                t.patient.membershipId || t.isShareMember || (t.patient.membershipId = n.id)
            }
        },
        ni = function() {
            var n = r.open({
                animation: !0,
                backdrop: "static",
                template: "<membership-card-view><\/membership-card-view>",
                controller: "MembershipCardCtrl",
                windowClass: "membership-dialog",
                size: "sm",
                resolve: {
                    host: function() {
                        return {
                            patient: t.patient
                        }
                    }
                }
            });
            n.result.then(function(n) {
                ut(n);
                o.publish(o.events.PatientChanged, t.patient, "PatientRecordCtrl")
            })
        },
        ti = function() {
            e.goToMembership(t.patient.id)
        },
        ii = function(n, i) {
            var u = r.open({
                animation: !0,
                backdrop: "static",
                template: "<patient-relation-edit-view><\/patient-relation-edit-view>",
                controller: "PatientRelationEditCtrl",
                size: "md",
                resolve: {
                    host: function() {
                        return {
                            patient: t.patient,
                            action: n || "add",
                            id: i
                        }
                    }
                }
            });
            u.result.then(function() {
                it(t.patient.id)
            })
        },
        ri = function(n) {
            v.confirm("删除关系人", "确定要删除此关系人？").then(function() {
                c.deleteRelation(n).success(function() {
                    it(t.patient.id)
                })
            })
        },
        ui = function(n) {
            u(function() {
                var i = r.open({
                    animation: !0,
                    backdrop: "static",
                    template: "<patient-photo-view><\/patient-photo-view>",
                    controller: "PatientPhotoCtrl",
                    size: "md",
                    resolve: {
                        host: function() {
                            return {
                                patient: t.patient,
                                event: n
                            }
                        }
                    }
                });
                i.result.then(function(n) {
                    ht(n)
                })
            })
        },
        fi = function() {
            w.getAvailablePatientTypes(t.patient.patientType).then(function(n) {
                t.isPatientTypeChangable = t.patient.officeId == y.officeId ? n.length > 0 : t.patient.patientType == h.tempPatientType
            })
        },
        ei = function() {
            w.changePatientType(t.patient).then(function() {
                e.reload()
            })
        },
        oi = function() {
            o.subscribe(t, o.events.PatientChanged, ct)
        },
        si = function() {
            o.unsubscribe(t, o.events.PatientChanged, ct)
        },
        hi = function() {
            g.unBindSaasPatient(t.patientId).success(function(n) {
                if (n) {
                    var i = t.findPatientTabManagerScope();
                    i && i.patientTabManager.activeTab && i.patientTabManager.activeTab.patient && i.patientTabManager.activeTab.patient.marketCenterAccount && (i.patientTabManager.activeTab.patient.marketCenterAccount = "");
                    t.patient.marketCenterAccount = ""
                } else d.error("解绑失败")
            }).error(function(t) {
                d.error("解绑失败");
                t.name == "ScrmException" && n.log("调用SCRM解绑接口失败");
                n.log(t)
            })
        },
        ct = function(n, i, r) {
            r != "PatientRecordCtrl" && t.patient && t.patient.id == i.id && st()
        },
        ci = function() {
            c.generatePatientQrCode(t.patient.id).then(function(n) {
                if (n == null || !n) {
                    v.warn("提示", "当前诊所未开通微诊所,无法绑定微信！");
                    return
                }
                c.sendPatientQrCode(t.patient.id);
                var i = {
                        interval: 3e3,
                        delay: 100,
                        maxCount: 20,
                        bindWeiXin: !0,
                        queryFunc: vi
                    },
                    u = r.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<qrcode-dialog><\/qrcode-dialog>",
                        controller: "QrcodeDialogCtrl",
                        size: "sm",
                        resolve: {
                            host: function() {
                                return {
                                    qrCode: n,
                                    outTradeNo: 1,
                                    isMarketCenter: !1,
                                    queryOption: i
                                }
                            }
                        }
                    });
                u.result.then(function() {
                    c.getPatient(t.patient.id).success(function(n) {
                        t.patient = n;
                        n && n.marketCenterAccount && d.success("微信绑定成功")
                    })
                })
            })
        },
        li = function() {
            t.$parent.switchState("marketingCenter.marketingSingleConsult")
        },
        ai = function() {
            k.getSystemConfigByType("PatientRequired").success(function(n) {
                t.officeSetting = n;
                t.systemConfigs = {};
                var i = t.officeSetting;
                angular.forEach(t.officeSetting, function(n) {
                    n.configName == "mobile" && n.configValue.toUpperCase() == "TRUE" ? t.requiredMobile = !0 : n.configName == "phoneNumber" && n.configValue.toUpperCase() == "TRUE" && (t.requiredPhoneNumber = !0)
                })
            })
        },
        vi = function() {
            var n = i.defer();
            return c.getPatient(t.patientId).success(function(t) {
                t.marketCenterAccount && n.resolve({
                    result: !0
                })
            }), n.promise
        };
    (function() {
        t.picture = {};
        t.phoneNumberList = [];
        t.mobileList = [];
        t.requiredMobile = !1;
        t.requiredPhoneNumber = !1;
        t.isEditMode = !1;
        t.edit = at;
        t.cancel = vt;
        t.save = wt;
        t.setSex = lt;
        t.openCard = ni;
        t.unBindPatientWeiXin = hi;
        t.goToMembershipDetail = ti;
        t.editRelation = ii;
        t.deleteRelations = ri;
        t.onClickFileDialog = ui;
        t.changePatientType = ei;
        t.getPatientQrcode = ci;
        t.openWxConversation = li;
        t.onRefereeSelected = yt;
        t.onLostFocused = pt;
        st();
        oi();
        ai();
        k.getItemTypes("mobileAttribute").success(function(n) {
            t.mobileAttribute = n
        });
        k.getItemTypes("phoneNumberAttribute").success(function(n) {
            t.phoneNumberAttribute = n
        });
        t.$on("$destroy", function() {
            si()
        })
    })()
}]);
var patient;
(function() {
    patientModule.controller("PatientApptRecordCtrl", ["$log", "$scope", "$modal", "$q", "$filter", "$injector", "eventAggregator", "enums", "appointmentSvc", "officeOptionSvc", "reportSvc", "apptUtil", "loginContext", "patientSvc", "patientUtil", "aresDialog", "userOptionSvc", "dataDicSvc", "appointmentSourceSvc", "moduleUtil", "imagingSvc", "apptApplyCompleteUtil", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b, k, d, g, nt) {
        "use strict";
        var ut = u("toApptStateString"),
            ft = u("toAppointmentTypeStr"),
            et = function(n) {
                y.editFollowUpApptById(n).then(function() {
                    tt()
                })
            },
            ot = function(n) {
                n.patientId = t.patientId;
                v.getPatient(t.patientId).success(function(r) {
                    if (n.patient = r, n && n.sourceType === "dp") return p.info("信息", "点评预约不能取消!"), !1;
                    if (n && n.sourceType === "wesure") return p.info("信息", "微保预约在确认后不能取消!"), !1;
                    var u = i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<appt-card-lite-view><\/appt-card-lite-view>",
                        controller: "ApptCardLiteCtrl",
                        resolve: {
                            apptHost: function() {
                                return {
                                    operation: "cancel",
                                    officeId: t.officeId,
                                    appointment: n
                                }
                            }
                        }
                    });
                    u.result.then(function() {
                        tt()
                    })
                })
            },
            st = function(n) {
                v.getLitePatient(t.patientId).success(function(t) {
                    var i = {
                        id: n,
                        patient: {
                            name: t.name
                        }
                    };
                    l.deletePendingAppt(i).then(function() {
                        tt()
                    })
                })
            },
            ht = function(n, t, i) {
                angular.forEach(n, function(n) {
                    var u, r, f;
                    n.stateStr = ut(n);
                    n.appointmentTypeStr = ft(n.appointmentType);
                    n.isHistory = Ares.isHistory(n.startTime);
                    u = (!n.isHistory || n.isHistory && n.isPending) && n.officeId == a.officeId;
                    n.canEdit = u && l.canEdit(n);
                    n.canCancel = u && l.canCancel(n);
                    n.showEmrBtn = !1;
                    n.showOrthdonticBtn = !1;
                    _.each(n.medicalRecordLites, function(t) {
                        t.id && t.medicalRecordType === 0 ? n.showEmrBtn = !0 : t.id && t.medicalRecordType === 1 && (n.showOrthdonticBtn = !0)
                    });
                    r = _.find(t, function(t) {
                        return t.appointmentId == n.id
                    });
                    n.sourceLevel1 = r ? r.sourceLevel1 : "";
                    n.sourceLevel2 = r ? r.sourceLevel2 : "";
                    n.sourceLevel3 = r ? r.sourceLevel3 : "";
                    n.doctorId && n.doctorId > 0 && (f = _.find(i, function(t) {
                        return t.id == n.doctorId
                    }), f && (n.doctorDepartment = f.department));
                    n.doctorDepartment || (n.doctorDepartment = "未知科室")
                })
            },
            tt = function() {
                s.getPatientAppts(t.patientId).success(function(n) {
                    var i = _.pluck(n, "id"),
                        u = k.getAppointmentSourceByApptIds(i),
                        f = b.providerDic.load();
                    r.all([u, f]).then(function(i) {
                        var r = i[0],
                            u = i[1];
                        ht(n, r, u);
                        t.allAppts = angular.copy(n);
                        it()
                    })
                })
            },
            ct = function() {
                at().then(function() {
                    it()
                })
            },
            it = function() {
                if (t.allAppts != null) {
                    var n = angular.copy(t.allAppts);
                    t.includeCanceled || (n = _.filter(n, function(n) {
                        return n.stateStr != "已取消"
                    }));
                    t.includeFailed || (n = _.filter(n, function(n) {
                        return n.stateStr != "失约"
                    }));
                    t.includePending || (n = _.filter(n, function(n) {
                        return n.stateStr != "待定"
                    }));
                    t.includeAppoint || (n = _.filter(n, function(n) {
                        return n.appointmentTypeStr != "预约"
                    }));
                    t.includeArrive || (n = _.filter(n, function(n) {
                        return n.appointmentTypeStr != "到店"
                    }));
                    t.apptList = n
                }
            },
            lt = function(n) {
                l.showApptAuditLog(n.id)
            },
            rt = function(n) {
                n || n == "" ? (t.includeCanceled = n.indexOf("includeCanceled") > -1 ? !0 : !1, t.includeFailed = n.indexOf("includeFailed") > -1 ? !0 : !1, t.includePending = n.indexOf("includePending") > -1 ? !0 : !1, t.includeAppoint = n.indexOf("includeAppoint") > -1 ? !0 : !1, t.includeArrive = n.indexOf("includeArrive") > -1 ? !0 : !1) : (t.includeCanceled = !0, t.includeFailed = !0, t.includePending = !0, t.includeAppoint = !0, t.includeArrive = !0)
            },
            at = function() {
                var i = r.defer(),
                    n = [],
                    u;
                return t.includeCanceled && n.push("includeCanceled"), t.includeFailed && n.push("includeFailed"), t.includePending && n.push("includePending"), t.includeAppoint && n.push("includeAppoint"), t.includeArrive && n.push("includeArrive"), u = n.join(","), w.setUserOption(w.userOptionKey.apptRecord, u).then(function(n) {
                    rt(n);
                    i.resolve(!0)
                }), i.promise
            },
            vt = function() {
                var n = r.defer();
                return w.getUserOption(w.userOptionKey.apptRecord).then(function(t) {
                    rt(t);
                    n.resolve(!0)
                }), n.promise
            },
            yt = function() {
                var n = r.defer();
                return h.getOfficeOption(h.optionKeys.IsAppointmentSourceEnabled).then(function(i) {
                    t.isAppointmentSourceEnabled = i;
                    n.resolve()
                }), n.promise
            },
            pt = function() {
                b.enabledChannelsDic.load().then(function(n) {
                    t.channels = n
                })
            },
            wt = function(n) {
                return nt.canComplete(n.sourceType) && n.apptApplyOrderData && !n.isCancelled && n.apptApplyOrderData.itemType == 0 && n.appointmentApplyProcessStatus != "创建后取消" && n.appointmentApplyProcessStatus != "改约申请" ? !0 : !1
            },
            bt = function(n) {
                var i = kt(n.sourceType);
                n.patientId = t.patientId;
                nt.complete(t.channels, n).then(function() {
                    tt()
                })
            },
            kt = function(n) {
                return nt.getSourceTypeName(n, t.channels)
            };
        (function() {
            t.channels = [];
            t.includeCanceled = !1;
            t.includeFailed = !1;
            t.includePending = !1;
            t.includeAppoint = !1;
            t.includeArrive = !1;
            t.canComplateApply = wt;
            t.complateApptApply = bt;
            t.editAppt = et;
            t.cancelAppt = ot;
            t.deleteAppt = st;
            t.showApptAuditLog = lt;
            t.filterAppts = ct;
            pt();
            yt();
            vt().then(function() {
                tt()
            })
        })()
    }])
})(patient || (patient = {}));
patientModule.controller("PatientBatchEditCtrl", ["$log", "$q", "$scope", "host", "$timeout", "$modalInstance", "aresNotification", "patientSvc", "loginContext", "aresDialog", function(n, t, i, r, u, f, e, o, s, h) {
    "use strict";
    var c = function() {
            f.dismiss("cancel")
        },
        l = function() {
            return i.targetType == "sourceType" && !i.patient.sourceTypeLevel1 ? (e.error("请选择患者来源"), !1) : i.targetType == "attendant" && !i.patient.attendantId ? (e.error("专属客服"), !1) : !0
        },
        a = function() {
            l() && h.confirm("提醒", "该操作将修改" + i.patientCount + "位患者的患者来源，确认后将立即生效，是否继续?").then(function() {
                var n, t, r;
                i.criteria ? (n = {
                    providerId: s.providerId,
                    criteria: i.criteria.filter,
                    isSearchPatientByDB: i.criteria.isSearchPatientByDB,
                    sourceTypeLevel1: i.patient.sourceTypeLevel1,
                    sourceType: i.patient.sourceType,
                    refereeName: i.patient.refereeName,
                    refereeId: i.patient.refereeId,
                    targetType: i.targetType
                }, o.batchEditPatientSourceTypeAsync(n).success(function() {
                    e.success("您的批量操作处理需要一定时间，请稍后查看处理结果");
                    f.close(!0)
                })) : (t = _.pluck(i.patients, "id"), r = {
                    patientIds: t,
                    sourceTypeLevel1: i.patient.sourceTypeLevel1,
                    sourceType: i.patient.sourceType,
                    refereeName: i.patient.refereeName,
                    refereeId: i.patient.refereeId,
                    attendantId: i.patient.attendantId,
                    targetType: i.targetType
                }, o.batchEditPatients(r).success(function() {
                    e.success("保存成功");
                    f.close(!0)
                }))
            })
        };
    (function() {
        i.cancel = c;
        i.title = r.title;
        i.save = a;
        i.patients = r.patients || [];
        i.patientCount = r.patientCount;
        i.criteria = r.criteria;
        i.targetType = r.targetType
    })()
}]);
patientModule.controller("PatientChoiceChargeCtrl", ["$log", "$scope", "eventAggregator", "$state", "$modal", "appNav", "patientSvc", "practiceSvc", "appointmentSvc", "aresDialog", "officeSvc", function(n, t, i, r, u, f, e, o, s, h, c) {
    "use strict";
    var l = function() {
            r.params.status == 5 ? t.allowNewCharge ? f.switchState("patientCharge.createNewPast", {
                patientId: r.params.patientId,
                chargeOrderId: 0,
                status: 0
            }) : f.switchState("patientCharge.createPast", {
                patientId: r.params.patientId,
                chargeOrderId: 0,
                status: 0
            }) : f.switchState("patientCharge.createRecord", {
                patientId: r.params.patientId,
                chargeOrderId: 0,
                status: 0
            })
        },
        a = function() {
            r.params.status == 5 ? t.allowNewCharge ? f.switchState("patientCharge.createNewSimplePast", {
                patientId: r.params.patientId,
                chargeOrderId: 0,
                status: 0
            }) : f.switchState("patientCharge.createSimplePast", {
                patientId: r.params.patientId,
                chargeOrderId: 0,
                status: 0
            }) : f.switchState("patientCharge.createEasyRecord", {
                patientId: r.params.patientId,
                chargeOrderId: 0,
                status: 0
            })
        },
        v = function() {
            f.switchState("patientCharge.createCdtRecord", {
                patientId: r.params.patientId,
                chargeOrderId: 0,
                status: 0
            })
        },
        y = function() {
            r.params.status == 5 ? t.allowNewCharge ? f.switchState("patientCharge.createNewDisposalDetailPast", {
                patientId: r.params.patientId,
                chargeOrderId: 0,
                status: 0
            }) : f.switchState("patientCharge.createDisposalDetailPast", {
                patientId: r.params.patientId,
                chargeOrderId: 0,
                status: 0
            }) : f.switchState("patientCharge.createDisposalDetailRecord", {
                patientId: r.params.patientId,
                chargeOrderId: 0,
                status: 0
            })
        },
        p = function() {
            c.getOfficeSetting().success(function(n) {
                t.officeSetting = n;
                t.systemConfigs = {};
                var i = t.officeSetting.systemConfigs;
                angular.forEach(t.officeSetting.systemConfigs, function(n) {
                    n.configName == "AllowNewCharge" && (t.allowNewCharge = n.configValue.toUpperCase() == "TRUE" ? !0 : !1)
                })
            })
        };
    (function() {
        p();
        t.status = r.params.status;
        t.createRecord = l;
        t.createEasyRecord = a;
        t.createCDTRecord = v;
        t.createDisposalRecord = y
    })()
}]);
patientModule.controller("PatientConsultRecordCtrl", ["$log", "$scope", "$sce", "$modal", "eventAggregator", "enums", "appointmentConsultSvc", "reportSvc", "apptUtil", "loginContext", "patientSvc", "$q", "dataDicSvc", "onlineConsultSvc", "aresSlidePanel", "patientUtil", "officeOptionSvc", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w) {
    "use strict";
    var b = function() {
            var i = {
                    patientId: t.patientId
                },
                n = t.isPersonalLevel ? !1 : !0;
            v.getPatientOnlineConsults(t.patientId, n).success(function(n) {
                angular.forEach(n, function(n) {
                    var i, r, u;
                    n.channel == f.AppointmentConsultChannel.Offline ? (n.statusStr = n.state ? "已成交" : "未成交", n.startTime = n.apptStartTime, n.endTime = n.apptEndTime, i = _.find(t.users, function(t) {
                        return t.id == n.recordCreatedUser
                    }), n.createUserName = i ? i.name : "", n.canEdit = d(n), n.isOnline = !1) : (n.startTime = n.recordCreatedTime, n.isOnline = !0, n.result = n.result == "consume-intention" ? " <span class='consult-record-consume-intention'>有意向<\/span>" : "<span class='consult-record-consume-none'>无意向<\/span>", r = n.description ? n.description : "", n.description = n.result + r, u = n.consultContent ? n.consultContent : "", n.consultContent = u)
                });
                t.consultList = _.sortBy(n, function(n) {
                    return n.startTime
                }).reverse()
            })
        },
        k = function(n) {
            if (n) {
                n = n.replace(/\n/g, "<br/>").replace(/  /g, "&nbsp;");
                return i.trustAsHtml(n)
            }
            return ""
        },
        d = function(n) {
            return n.channel == f.AppointmentConsultChannel.Offline && n.officeId == h.officeId ? h.roleType == "诊所管理员" || h.roleType == "公司管理员" ? !0 : h.userId == n.recordCreatedUser ? !0 : !1 : !1
        },
        g = function() {
            var n = l.defer();
            return a.userNameDic.load().then(function(i) {
                t.users = i;
                n.resolve(!0)
            }), n.promise
        },
        nt = function(n) {
            var i = _.find(t.consultList, function(t) {
                    return t.id == n
                }),
                u = r.open({
                    animation: !0,
                    backdrop: "static",
                    template: "<appointment-consult-view><\/appointment-consult-view>",
                    controller: "AppointmentConsultCtrl",
                    windowClass: "consult-card-dialog",
                    size: "lg",
                    resolve: {
                        apptHost: function() {
                            return {
                                patientId: t.patientId,
                                apptData: i.appointment,
                                isFirstVisit: i.appointment.isFirstVisit,
                                needRefreshPatientConsultant: !1
                            }
                        }
                    }
                });
            u.result.then(function() {
                b()
            })
        },
        tt = function() {
            var n;
            h.providerJob == "网电营销" ? (n = y.open("<online-consult-detail-edit-view><\/online-consult-detail-edit-view>", "OnlineConsultDetailEditCtrl", {
                host: function() {
                    return {
                        title: "新建咨询",
                        patientId: t.patientId,
                        isCheckedInToday: t.isCheckedInToday,
                        isStrongStrict: t.isStrongStrict
                    }
                }
            }, t), n.result.then(function() {
                b()
            })) : (n = r.open({
                animation: !0,
                backdrop: "static",
                template: "<appointment-consult-view><\/appointment-consult-view>",
                controller: "AppointmentConsultCtrl",
                windowClass: "consult-card-dialog",
                size: "lg",
                resolve: {
                    apptHost: function() {
                        return {
                            patientId: t.patientId,
                            apptData: null,
                            isFirstVisit: !1,
                            needRefreshPatientConsultant: !1,
                            isCheckedInToday: t.isCheckedInToday,
                            isStrongStrict: t.isStrongStrict,
                            isAppointmentConsultAppendable: t.isAppointmentConsultAppendable
                        }
                    }
                }
            }), n.result.then(function() {
                b()
            }));
            Ares.sensors.track("PatientConsultRecordOperation", {
                OperationType: "新建咨询"
            })
        },
        it = function() {
            p.hasCheckedInToday(t.patientId).then(function(n) {
                t.isCheckedInToday = n.isCheckedIn;
                t.isStrongStrict = n.isStrongStrict;
                t.initCreateConsultRecord()
            })
        },
        rt = function() {
            var n = l.defer();
            return w.getOfficeOption(w.optionKeys.IsAppointmentConsultAppendable).then(function(i) {
                t.isAppointmentConsultAppendable = i;
                n.resolve(i)
            }), n.promise
        };
    (function() {
        t.convertToHtml = k;
        t.consultAppt = nt;
        t.createConsult = tt;
        g().then(function() {
            b()
        });
        rt().then(function() {
            it()
        });
        t.isCheckedInToday = !1;
        t.isStrongStrict = !1;
        t.isAppointmentConsultAppendable = !1
    })()
}]);
patientModule.controller("PatientDiagnoseRecordCtrl", ["$log", "$scope", "$modal", "$q", "eventAggregator", "enums", "appointmentSvc", "userOptionSvc", "aresDialog", "apptUtil", "loginContext", "patientSvc", "appNav", "permissionProvider", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v) {
    "use strict";
    t.findText = "";
    var p = function() {
            var n = r.defer();
            return l.getPatientHistoryDiagnose(t.patientId, t.findText).success(function(i) {
                for (var u, f, e, o, r = 0; r < i.length; r++) {
                    for (i[r].createDateStr = moment(i[r].createDate).format("YYYY-MM-DD"), i[r].isShow = !0, u = 0; u < i[r].diagnoseMtoLiset.length; u++)
                        if (i[r].diagnoseMtoLiset[u].fdiToothCodes == null && (i[r].diagnoseMtoLiset[u].fdiToothCodes = ""), i[r].diagnoseMtoLiset[u].fdiToothCodes != null)
                            for (i[r].diagnoseMtoLiset[u].fdiToothCodesArray = i[r].diagnoseMtoLiset[u].fdiToothCodes.split(","), i[r].diagnoseMtoLiset[u].isFind = !0, f = 0; f < t.findeFDIToothCodesArray.length; f++)
                                if (i[r].diagnoseMtoLiset[u].fdiToothCodes.indexOf(t.findeFDIToothCodesArray[f]) <= -1) {
                                    i[r].diagnoseMtoLiset[u].isFind = !1;
                                    break
                                }
                    for (e = 0; e < i[r].diagnoseMtoLiset.length; e++)
                        if (i[r].diagnoseMtoLiset[e].isFind == !0) {
                            i[r].isShow = !0;
                            break
                        }
                    i[r].procedures && (o = [], angular.forEach(i[r].procedures, function(n) {
                        o.push(n.transaction.name)
                    }), i[r].transactionNames = o.join(","))
                }
                t.patientDiagnoseList = i;
                n.resolve(!0)
            }), n.promise
        },
        tt = function(n, t) {
            $state.transitionTo(n, t, {})
        },
        w = function(n) {
            l.getMedicalRecord(n.id).success(function(n) {
                b(n)
            })
        },
        b = function(n) {
            k(n) ? n.isAllowEdit == 1 ? a.goToEditEMR(n.patientId, {
                patientId: n.patientId,
                medicalRecordId: n.id
            }) : n.isAllowEdit == 2 ? s.info("提醒", "该病历超出病历时限范围，不允许修改！") : l.isAllowEditMedicalRecordByTimeLimit(n.id).success(function(t) {
                t ? (n.isAllowEdit = 1, a.goToEditEMR(n.patientId, {
                    patientId: n.patientId,
                    medicalRecordId: n.id
                })) : (n.isAllowEdit = 2, s.info("提醒", "该病历超出病历时限范围，不允许修改！"))
            }) : s.info("提醒", "当前用户没有权限编辑该病历！")
        },
        k = function(n) {
            return n.recordCreatedUser == c.userId || n.doctorId == c.providerId || v.isAllowed("patientMedicalRecord.alterOther") ? !0 : !1
        },
        d = function(n) {
            t.savePageState();
            l.getPatient(t.patientId).success(function(i) {
                a.goToCharge(i);
                a.switchState("patientCharge.createDisposalDetailRecord", {
                    patientId: t.patientId,
                    chargeOrderId: n.id,
                    status: 0
                })
            })
        },
        g = function() {
            p().then(function() {
                y()
            })
        },
        nt = function() {
            var n = r.defer();
            return o.getUserOption(o.userOptionKey.diagnoseRecordOption).then(function(i) {
                t.option = i;
                n.resolve(!0)
            }), n.promise
        },
        y = function() {
            var n = t.option;
            o.setUserOption(o.userOptionKey.diagnoseRecordOption, n).then(function() {
                var n = angular.copy(t.patientDiagnoseList);
                t.option.includeEmrRecord || (n = _.filter(n, function(n) {
                    return n.type != "电子病历"
                }));
                t.option.includeDiagnoseChargeOrder || (n = _.filter(n, function(n) {
                    return n.type != "处置收费"
                }));
                t.patientHistoryDiagnoseList = n
            })
        };
    (function() {
        t.findeFDIToothCodesArray = {};
        nt().then(function() {
            p().then(function() {
                y();
                t.setPageState()
            })
        });
        t.goToEMR = w;
        t.goToCharge = d;
        t.search = g;
        t.filterRecords = y
    })()
}]);
patientModule.controller("DrugDictConfigController", ["$log", "$scope", "$modalInstance", "host", function(n, t, i, r) {
    "use strict";
    t.durgDict = {};
    var u = function() {
            i.close(t.durgDict)
        },
        f = function() {
            r.durgDict && (t.durgDict = r.durgDict)
        };
    (function() {
        f();
        t.cancel = u
    })()
}]);
patientModule.controller("PatientDrugOrderEditCtrl", ["$log", "$q", "$scope", "$sce", "$timeout", "$compile", "$location", "$http", "$state", "$modal", "appNav", "enums", "patientSvc", "practiceSvc", "constants", "appointmentSvc", "aresDialog", "loginContext", "drugOrderPrint", "workflowSvc", "patientUtil", "providerUtil", "dataDicSvc", "chargeSvc", "approvalUtil", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b, k, d, g, nt, tt, it, rt) {
    "use strict";
    i.data = {
        durgDict: {}
    };
    i.oldDrugOrder = {};
    i.updateDrugOrderGridDataSource = function(n) {
        var t = $("#drugOrderDetailGrid").data("kendoGrid"),
            i = new kendo.data.DataSource({
                data: n,
                schema: {
                    model: {
                        id: "id",
                        fields: {
                            drugName: {
                                type: "string",
                                editable: !1
                            },
                            specifications: {
                                type: "string",
                                editable: !1
                            },
                            unit: {
                                type: "string",
                                editable: !1
                            },
                            count: {
                                type: "number",
                                validation: {
                                    required: !0,
                                    min: 1
                                }
                            },
                            usage: {
                                type: "string",
                                editable: !0
                            }
                        }
                    }
                }
            });
        t.setDataSource(i)
    };
    i.editBasicDict = function() {
        var n = h.open({
            animation: !0,
            backdrop: "static",
            template: "<patient-drug-dict-config><\/patient-drug-dict-config>",
            controller: "DrugDictConfigController",
            windowClass: "drugdictconfig-dialog",
            size: "sm",
            resolve: {
                host: function() {
                    return {
                        durgDict: angular.copy(i.data.durgDict)
                    }
                }
            }
        });
        n.result.then(function(n) {
            i.data.durgDict = angular.copy(n);
            i.updateDrugDictGridDataSource()
        })
    };
    i.saveDrugOrder = function() {
        var r = t.defer(),
            e = $("#doctor").data("kendoNameCodeFilterComboBox"),
            u, f, n;
        if ((i.currentDrugOrder.doctorName = e.text(), i.currentDrugOrder.doctorId = e.value(), u = $("#appoint").data("kendoDropDownList"), !u) || (i.currentDrugOrder.appointId = u.value(), !i.currentDrugOrder.appointId)) return w.warn("信息", "没有关联的就诊时间，请先创建一次预约，填写就诊病历！"), r.promise;
        if (f = $("#drugOrderDetailGrid").data("kendoGrid"), f.saveChanges(), i.currentDrugOrder.drugOrderDetailList = f.dataSource._data, i.currentDrugOrder.drugOrderDetailList.length == 0) return w.warn("信息", "没有选择药品，请选择药品！"), r.promise;
        for (n = 0; n < i.currentDrugOrder.drugOrderDetailList.length; ++n) i.currentDrugOrder.drugOrderDetailList[n].did == 0 && (i.currentDrugOrder.drugOrderDetailList[n].did = i.currentDrugOrder.drugOrderDetailList[n].id), i.currentDrugOrder.drugOrderDetailList[n].id <= 0 && (i.currentDrugOrder.drugOrderDetailList[n].id = 0);
        return i.currentDrugOrder.id == 0 ? a.createDrugOrder(i.currentDrugOrder).success(function(n) {
            ft(n);
            w.info("信息", "保存成功").then(function() {
                i.oldDrugOrder = angular.copy(i.currentDrugOrder);
                r.resolve(!0)
            })
        }).error(function(n) {
            n.name == "DrugOrderRequireApproveException" ? ut(n.message, n.data) : (w.warn("信息", "保存失败"), r.reject(!1))
        }) : a.updateDrugOrder(i.currentDrugOrder).success(function() {
            w.info("信息", "保存成功").then(function() {
                i.oldDrugOrder = angular.copy(i.currentDrugOrder);
                r.resolve(!0)
            })
        }).error(function(n) {
            n.name == "DrugOrderRequireApproveException" ? ut(n.message, n.data) : w.warn("信息", "保存失败");
            r.reject(!1)
        }), r.promise
    };
    var ut = function(n, t) {
            var r = JSON.parse(t);
            rt.approvalConfirmDialog("带教老师处方审批确认", n, r).then(function(n) {
                i.currentDrugOrder.actorIds = n;
                d.applyDrugOrderWorkflow(i.currentDrugOrder).success(function(n) {
                    ft(n);
                    i.disableEdit();
                    w.info("信息", "处方审批提交成功").then(function() {
                        return i.oldDrugOrder = angular.copy(i.currentDrugOrder), !0
                    })
                }).error(function(n) {
                    return n.name != "AresBusinessException" && w.warn("提示", "处方审批提交失败"), !1
                })
            })
        },
        ft = function(n) {
            var t = _.find(i.historyAppts, function(t) {
                return t.id == n.appointId
            });
            t && (n.appointTime = t.startTimeStr);
            i.currentDrugOrder = n
        },
        ht = function() {
            i.currentDrugOrder && i.currentDrugOrder.id == 0 || i.getDrugOrderIsChange() ? w.confirm("提醒", "保存后才能打印，确认保存并打印？").then(function() {
                i.saveDrugOrder().then(function() {
                    et()
                })
            }) : et()
        },
        et = function() {
            var n = new k.DrugOrderPrinter;
            n.setTemplateBaseData({
                $scope: i,
                office: i.office,
                patient: i.patient,
                currentDrugOrder: i.currentDrugOrder
            }).setPrintTemplateInfo({
                isPrivateTemplate: !1,
                templateCode: "drugorderPrintDiv"
            }, "Custom").setOptions({
                isNeedBaseData: !0
            }).print()
        },
        ct = function() {
            v.getOffice(b.officeId).success(function(n) {
                i.office = n
            })
        },
        ot = function() {
            i.systemConfig.ConfigName = "drugorder";
            i.systemConfig.Coments = "drugorderPrint";
            v.getSystemConfig(i.systemConfig).success(function(n) {
                n && (i.systemConfig.templateType = n.configValue)
            })
        },
        lt = function() {
            var n = h.open({
                animation: !0,
                backdrop: "static",
                template: "<emr-print-configuration-view><\/emr-print-configuration-view>",
                controller: "emrPrintConfigurationCtrl",
                size: "lg",
                resolve: {
                    host: function() {
                        return {
                            template: "drugorder"
                        }
                    }
                }
            });
            n.result.then(function() {
                ot()
            })
        },
        dt = function(n) {
            var r = t.defer();
            return n && n.doctorId ? nt.getProviderEmployeeSignature(i.providerPictures, n.doctorId, i).then(function(t) {
                n.employeeSignature = t && t.filePath ? t : null;
                r.resolve()
            }) : r.resolve(), r.promise
        },
        st = function(n) {
            var r = t.defer();
            return n || r.resolve(), it.getYibaoOrdeDataByAppoint(n).then(function(n) {
                var t, f, e, o, u;
                n.data.items ? (i.currentDrugOrder.drugOrderDetailList = [], t = n.data, f = t.items, f && f.length > 0 && (e = f.map(function(n) {
                    var t = n.chargeItem;
                    return {
                        drugName: t.name,
                        specifications: "",
                        unit: t.unit,
                        usage: "",
                        price: t.price,
                        count: n.amount,
                        did: -1
                    }
                }), i.currentDrugOrder.drugOrderDetailList = i.currentDrugOrder.drugOrderDetailList.concat(e)), t.doctor && t.doctor.id && t.doctor.id > 0 && (o = i.element.find("#doctor").data("kendoNameCodeFilterComboBox"), o.value(t.doctor.id)), t.diagnoses && t.diagnoses.length > 0 && (u = "", t.diagnoses.forEach(function(n) {
                    u += n.name + ","
                }), u = u.substr(0, u.length - 1), i.currentDrugOrder.diagnosis = u), i.currentDrugOrder.clinicNo = t.serialNumber, i.currentDrugOrder.feeType = "医保", i.setFeeType("医保"), i.initDetailGrid(i.currentDrugOrder.drugOrderDetailList, !0), r.resolve()) : (i.currentDrugOrder.feeType = "自费", i.currentDrugOrder.diagnosis || (i.currentDrugOrder.diagnosis = ""), i.initDetailGrid(i.currentDrugOrder.drugOrderDetailList, !0), r.resolve())
            }), r.promise
        },
        at = function() {
            var n = [pt(), bt(), kt()];
            vt().then(function() {
                return wt(), yt()
            }).then(function() {
                return t.all(n)
            }).then(function() {
                i.currentDrugOrder.clinicCardNo = i.patient.extension.yibaoAccountNo;
                i.updateDrugOrderGridDataSource(i.currentDrugOrder.drugOrderDetailList);
                i.currentDrugOrder.workflowStatus && i.currentDrugOrder.workflowStatus > 0 && u(function() {
                    i.disableEdit()
                });
                u(function() {
                    if (i.historyAppts && i.historyAppts.length > 0) {
                        var n = i.historyAppts[0].id;
                        st(n).then(function() {
                            i.oldDrugOrder = angular.copy(i.currentDrugOrder)
                        })
                    }
                })
            })
        },
        vt = function() {
            var n = t.defer();
            return i.currentOrderId > 0 ? a.getDrugOrder(i.currentOrderId).success(function(t) {
                i.currentDrugOrder = t;
                i.setFeeType(t.feeType);
                n.resolve()
            }) : i.currentOrderId == 0 && (i.currentDrugOrder = {
                id: 0,
                pid: i.patientId,
                orderDataTime: moment(new Date).format("YYYY-MM-DD HH:mm:ss"),
                drugOrderDetailList: [],
                doctorId: 0,
                doctorName: "",
                comments: ""
            }, u(function() {
                i.setFeeType("自费");
                n.resolve()
            })), n.promise
        },
        yt = function() {
            var n = t.defer();
            return a.getPatient(i.patientId).then(function(t) {
                var r, u, f;
                i.patient = t.data;
                i.patient.birth ? (r = moment(i.patient.birth, "YYYY-MM-DD"), r.isValid() || (r = moment(i.patient.birth, "YYYYMMDD")), r.isValid() && (u = moment(Ares.today()), f = u.diff(r, "years"), i.ignoreAgeChanged = !0, i.patient.age = f)) : i.patient.age = "";
                n.resolve()
            }), n.promise
        },
        pt = function() {
            var n = t.defer(),
                r = {
                    officeId: b.officeId,
                    patientId: i.patientId,
                    endTime: moment(Ares.today()).add(1, "d").format(y.dateFormat),
                    isCancelled: !1,
                    isPending: !1
                };
            return p.searchAppointments(r).success(function(t) {
                var u, r;
                for (t.length > 0 ? i.historyAppts = t : (i.historyAppts = null, n.resolve()), r = 0; r < i.historyAppts.length; ++r) i.historyAppts[r].startTimeStr = angular.copy(i.historyAppts[r].startTime), i.historyAppts[r].startTime = moment(i.historyAppts[r].startTime).format("YYYY年MM月DD日 HH:mm");
                if (u = i.element.find("#appoint").data("kendoDropDownList"), u) {
                    if (u.setDataSource(i.historyAppts), i.currentDrugOrder)
                        if (i.currentDrugOrder.appointId && i.currentDrugOrder.appointId != 0) {
                            for (r = 0; r < i.historyAppts.length; ++r)
                                if (i.historyAppts[r].id == i.currentDrugOrder.appointId) {
                                    i.currentDrugOrder.appointTime = i.historyAppts[r].startTimeStr;
                                    i.drugOrderAppt = i.historyAppts[r];
                                    u && u.select(r);
                                    break
                                }
                        } else i.currentDrugOrder.appointTime = i.historyAppts[0].startTimeStr, i.drugOrderAppt = i.historyAppts[0], u && u.select(0);
                    i.isEdit || u.enable(!1)
                }
                n.resolve()
            }), n.promise
        },
        wt = function() {
            var n = t.defer();
            return v.getDoctors().success(function(t) {
                i.doctors = t;
                i.initDoctorDropdownlist();
                i.drugDoctor = i.currentDrugOrder && i.currentDrugOrder.doctorId ? _.find(i.doctors, function(n) {
                    return n.id == i.currentDrugOrder.doctorId
                }) : b.providerJob == "医生" ? i.drugDoctor = _.find(i.doctors, function(n) {
                    return n.id == b.providerId
                }) : i.doctors && i.doctors.length > 0 ? i.doctors[0] : null;
                var r = i.drugDoctor ? i.drugDoctor.id : null;
                i.setDoctor(r);
                i.isEdit || doctorComboBox.enable(!1);
                n.resolve()
            }), n.promise
        },
        bt = function() {
            var n = t.defer();
            return a.getBodyCheck(i.patientId).success(function(t) {
                i.bodyCheck = t;
                n.resolve()
            }), n.promise
        },
        kt = function() {
            var n = t.defer();
            return tt.providerPictureDic.load().then(function(t) {
                var t = _.filter(t, function(n) {
                    return n.proivderPictureType == l.ProivderPictureType.Signature
                });
                i.providerPictures = t;
                n.resolve(t)
            }), n.promise
        };
    i.isEdit = !0;
    i.systemConfig = {};
    ct();
    ot();
    i.privateTemplate = {};
    i.toPrint = ht;
    i.patientId = s.params.patientId;
    i.appointId = s.params.apptId;
    i.currentOrderId = s.params.drugOrderId;
    i.editPrintSetting = lt;
    i.initDrugOrderByYibaoOrder = st;
    i.currentOrderId || (i.currentOrderId = 0);
    i.editstatus = s.params.status;
    at()
}]);
patientModule.controller("PatientDrugOrderCtrl", ["$log", "$scope", "$filter", "$state", "$q", "appNav", "patientSvc", "aresDialog", "loginContext", "dataDicSvc", "enums", function(n, t, i, r, u, f, e, o, s, h, c) {
    "use strict";
    t.data = {
        drugOrders: []
    };
    var l = i("toOfficeAbbr");
    t.listPatientDrugOrders = function() {
        e.listDrugOrdersForPatient(t.patientId).success(function(n) {
            for (var i = 0; i < n.length; i++) n[i].officeName = l(n[i].officeId), n[i].orderDataTime = moment(n[i].orderDataTime).format("YYYY-MM-DD HH:mm"), n[i].apptTime = moment(n[i].apptTime).format("YYYY-MM-DD HH:mm"), n[i].index = i + 1;
            t.data.drugOrders = n
        }).error(function(n) {
            t.data.drugOrders = [];
            t.data.error = n
        })
    };
    t.deleteDrugOrder = function(n) {
        o.confirm("提醒", "确定要删除此处方记录？").then(function() {
            e.deleteDrugOrder(n.id).success(function() {
                t.listPatientDrugOrders()
            }).error(function(n) {
                alert(n.data)
            })
        })
    };
    t.editDrugOrder = function(n) {
        if (n.officeId != s.officeId) {
            o.info("提示", "不可修改其他诊所的处方记录！");
            return
        }
        f.switchState("patientPrescription.createRecord", {
            patientId: t.patientId,
            drugOrderId: n.id,
            status: 1
        })
    };
    t.initData = function() {
        var i = u.defer(),
            n = [];
        return n.push(h.workflowDefinitionDic.load().then(function(n) {
            t.drugOrderWorkflow = _.find(n, function(n) {
                return n.workflowType == c.WorkflowType.InstructorDrugOrder
            })
        })), n.push(h.officeSettingDic.load().then(function(n) {
            t.isInternWorkflowEnabled = n.isInternWorkflowEnabled
        })), u.all(n).then(function() {
            i.resolve()
        }), i.promise
    };
    t.patientId = r.params.patientId;
    t.appointId = r.params.apptId;
    e.getPatient(t.patientId).success(function(n) {
        t.patient = n
    });
    h.officeDic.load().then(function(n) {
        t.officeList = n
    });
    t.officeId = s.officeId;
    t.isRegularChain = t.$root.isRegularChain;
    t.listPatientDrugOrders()
}]);
patientModule.controller("PatientFollowupCtrl", ["$q", "$scope", "$state", "patientSvc", "dataDicSvc", "loginContext", function(n, t, i, r, u, f) {
    "use strict";
    var e = function() {
        var i = n.defer();
        return r.listFollowupsForPatient(t.patientId, {
            orderField: "visitDateTime",
            orderDirection: "desc"
        }).success(function(n) {
            i.resolve(n)
        }), i.promise
    };
    (function() {
        t.patientId = i.params.patientId;
        u.officeDic.load().then(function(n) {
            t.officeList = n
        });
        t.officeId = f.officeId;
        t.getPatientFollowups = e
    })()
}]);
patientModule.controller("PatientInfoRecordCtrl", ["$log", "$scope", "$q", "$modal", "$timeout", "$filter", "appNav", "eventAggregator", "enums", "constants", "dataDicSvc", "aresDialog", "loginContext", "patientUtil", "permissionProvider", "systemConfigUtil", "aresNotification", "$rootScope", "patientTabManager", "officeOptionSvc", "patientSvc", "providerSvc", "membershipSvc", "reportSvc", "practiceSvc", "freeFieldSvc", "moduleOptionProvider", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b, k, d, g, nt, tt, it, rt, ut, ft) {
    "use strict";
    var st = function(n) {
            return c.patientTagDic.load().then(function(i) {
                return t.patientTags = angular.copy(i), g.getTagByPaitentId(n.id)
            }).then(function(i) {
                n.patientTagUseList = i.data ? i.data : [];
                var r = [];
                n.patientTagUseList && t.patientTags && (angular.forEach(t.patientTags, function(n) {
                    n.textColor = n.itemValue ? Ares.getForegroundColor(n.itemValue) : Ares.getForegroundColor("#fff")
                }), t.patientTags.forEach(function(t) {
                    var i = _.find(n.patientTagUseList, function(n) {
                        return n.tagId == t.id
                    });
                    i && (i.abbreviation = t.abbreviation, i.isHidden = t.isHidden, i.itemValue = t.itemValue, i.itemName = t.itemName, i.textColor = t.textColor, t.selected = !0, r.push(i))
                }), n.patientTagUseList = r, n.patientTagUseList.forEach(function(n) {
                    !n.abbreviation && n.itemName && (n.abbreviation = n.itemName.substring(0, 1))
                }))
            })
        },
        wt = function(n) {
            var r = i.defer();
            return n == s.SourceType.Friend ? (t.enableReferee = !0, t.enableProvider = !1, t.enableOtherSourceType = !1) : n == s.SourceType.Provider ? (t.enableProvider = !0, t.enableReferee = !1, t.enableOtherSourceType = !1) : n ? (t.enableReferee = !1, t.enableProvider = !1, t.enableOtherSourceType = !0) : (t.enableReferee = !1, t.enableProvider = !1, t.enableOtherSourceType = !1), r.resolve(), r.promise
        },
        bt = function() {
            var n = i.defer();
            return g.getRefereeCountByPatientId(t.patientId).success(function(i) {
                t.refereeCount = i;
                n.resolve()
            }), n.promise
        },
        kt = function(n) {
            var r = [];
            return r.push(c.doctorDic.loadActive().then(function(n) {
                t.doctors = n
            })), n.doctorId && r.push(nt.getName(n.doctorId).then(function(n) {
                n && (t.patient.doctorName = n)
            })), n.dutyDoctorId && r.push(nt.getName(n.dutyDoctorId).then(function(n) {
                t.patient.dutyDoctorName = n
            })), i.all(r)
        },
        dt = function(n) {
            var r = [];
            return r.push(c.consultantDic.loadActive().then(function(n) {
                t.consultants = n
            })), n.attendantId && r.push(nt.getName(n.attendantId).then(function(n) {
                t.patient.attendantName = n || ""
            })), i.all(r)
        },
        gt = function(n) {
            var r = i.defer();
            if (!n.advisorId) {
                r.resolve();
                return
            }
            return n.dutyDoctorId && n.dutyDoctorId == n.advisorId ? n.advisorName = t.patient.dutyDoctorName : n.consultantId && n.consultantId == n.advisorId && (n.advisorName = t.patient.consultantName), r.resolve(), r.promise
        },
        ni = function(n) {
            var r = [];
            return r.push(c.consultantDic.loadActive().then(function(n) {
                t.consultants = n
            })), r.push(c.webPhoneConsultantDic.loadActive().then(function(n) {
                t.onlineConsultants = n
            })), r.push(c.allProviderDic.loadActive().then(function(n) {
                t.developers = n
            })), n.consultantId && r.push(nt.getName(n.consultantId).then(function(n) {
                t.patient.consultantName = n || ""
            })), n.extension.onlineConsultantId && r.push(nt.getName(n.extension.onlineConsultantId).then(function(n) {
                t.patient.extension.onlineConsultantName = n || ""
            })), n.extension.developerId && r.push(nt.getName(n.extension.developerId).then(function(n) {
                t.patient.extension.developerName = n || ""
            })), i.all(r)
        },
        ti = function(n) {
            var r = i.defer();
            return n.membershipId ? tt.getMembership(n.membershipId).success(function(n) {
                t.isShareMember = !1;
                ht(n);
                r.resolve()
            }) : g.getMembership(n.id).success(function(n) {
                // n = null;
                n && (t.isShareMember = !0, ht(n));
                r.resolve()
            }), r.promise
        },
        ht = function(n) {
            if (n) {
                var i = c.membershipTypeDic.getItemSync(n.membershipTypeId);
                // var i = c.membershipTypeDic.cache[c.membershipTypeDic.cache.length - 1];
                n.membershipTypeName = i.name;
                t.membership = n;
                t.patient.membershipId || t.isShareMember || (t.patient.membershipId = n.id)
            }
        },
        ii = function(n) {
            var r = i.defer();
            return g.getBodyCheck(n).success(function(n) {
                var u, f, i;
                if (n) {
                    if (n.medicine) {
                        for (u = n.medicine.split(","), f = [], i = 0; i < u.length; i++) f[i] = u[i];
                        c.medicineDic.load().then(function(i) {
                            for (var u = _.map(i, function(n) {
                                    return n.itemName
                                }), r = 0; r < n.medicine.length; r++) _.indexOf(u, n.medicine[r]) == -1 && n.medicine[r] != "" && i.push({
                                itemName: n.medicine[r]
                            });
                            t.medicineLists = i
                        })
                    } else c.medicineDic.load().then(function(n) {
                        t.medicineLists = n
                    });
                    t.patient.bodycheck = n
                } else c.medicineDic.load().then(function(n) {
                    t.medicineLists = n
                }), t.patient.bodycheck = {};
                t.bodycheck = t.patient.bodycheck;
                r.resolve()
            }), r.promise
        },
        ct = function(n) {
            var r = i.defer();
            return it.GetPatientRelation(n).success(function(n) {
                for (var i = 0; i < n.length; ++i) n[i].sex = f("toSexString")(n[i].sex);
                t.patientRelation = n;
                r.resolve()
            }).error(function() {
                r.reject()
            }), r.promise
        },
        ri = function(n) {
            var r = [];
            return r.push(g.getMobileByPatientId(n).then(function(i) {
                var r = i.data,
                    u;
                r.length > 0 ? t.patient.mobileList = r : (t.patient.mobileList = [], u = {
                    mobile: "",
                    maskedMobile: "",
                    patientId: n,
                    attributes: "mobile",
                    displayOrder: 1,
                    mobileType: "本人"
                }, t.patient.mobileList.push(u))
            })), r.push(g.getPhoneNumberByPatientId(n).then(function(i) {
                var r = i.data,
                    u;
                r.length > 0 ? t.patient.phoneNumberList = r : (t.patient.phoneNumberList = [], u = {
                    mobile: "",
                    maskedMobile: "",
                    patientId: n,
                    attributes: "PhoneNumber",
                    displayOrder: 1,
                    mobileType: "家"
                }, t.patient.phoneNumberList.push(u))
            })), i.all(r)
        },
        ui = function(n) {
            var r = i.defer();
            return n.pictureId ? g.getPictureById(n.pictureId).success(function(n) {
                t.picture = n;
                r.resolve()
            }) : r.resolve(), r.promise
        },
        fi = function(n) {
            var r = i.defer();
            return ut.getPatientFreeFieldValue(n).success(function(i) {
                t.patientFreeField = i || {
                    targetType: 1,
                    targetId: n
                };
                r.resolve()
            }), r.promise
        },
        ei = function() {
            var n = i.defer();
            return v.getAvailablePatientTypes(t.patient.patientType).then(function(i) {
                t.patient.isPatientTypeChangable = t.patient.officeId == a.officeId ? i.length > 0 : !1;
                n.resolve()
            }), n.promise
        },
        et = function() {
            var n = i.defer();
            return g.getPatient(t.patientId).success(function(r) {
                console.log(r);
                if (t.patient = r, r.identityCard) {
                    var u = new RegExp("(\\d{6})(\\d*)(\\d{4})");
                    r.privacyIdentityCard = r.identityCard.replace(u, "$1*****$3")
                }
                return r.extension || (r.extension = {}), t.patient.refereeId > 0 && (t.refereePatient = {
                    id: t.patient.refereeId,
                    name: t.patient.refereeName,
                    mobile: t.patient.refereeMobileOrCode
                }), t.guardianCopy = t.patient.guardian ? angular.copy(t.patient.guardian) : null, r.birth && (r.birth = moment(r.birth, "YYYY-MM-DD").format("YYYY-MM-DD")), r.firstVisit && (r.firstVisit = moment(r.firstVisit, "YYYY-MM-DD").format("YYYY-MM-DD")), o.publish(o.events.PatientLoaded, r, "PatientInfoRecordCtrl"), i.all([st(r), wt(r.sourceType), bt(), kt(r), ni(r), dt(r), ti(r), ii(t.patientId), ct(t.patientId), ri(t.patientId), ui(r), ei(), fi(t.patientId), ]).then(function() {
                    gt(r);
                    n.resolve()
                })
            }), n.promise
        },
        oi = function() {
            g.generatePrivateId(t.patient.patientType).success(function(n) {
                t.patient.privateId = n
            })
        },
        si = function() {
            v.changePatientType(t.patient).then(function() {
                e.reload()
            })
        },
        hi = function() {
            var i, n;
            for (t.patient.mobile = t.patient.mobileList[0].mobile, t.patient.phoneNumber = t.patient.phoneNumberList[0].mobile, i = angular.copy(t.patient.mobileList), n = 0; n < t.patient.phoneNumberList.length; n++) i.push(t.patient.phoneNumberList[n]);
            t.patient.telephoneNumberList = i
        },
        lt = function() {
            var i = t.patient.patientTagUseList.map(function(n) {
                    return n.tagId
                }),
                n;
            k && k.activeTab && k.activeTab.patient && (n = [], angular.forEach(i, function(i) {
                var r = _.find(t.patientTags, {
                    id: i
                });
                r && (r.title = r.isHidden ? "" : r.itemName, r.firstLetter = r.abbreviation ? r.abbreviation : r.itemName.substring(0, 1), r.textColor = r.itemValue ? Ares.getForegroundColor(r.itemValue) : Ares.getForegroundColor("#fff"), n.push(r))
            }), k.activeTab.patient.tags = n)
        },
        ci = function() {
            var t = i.defer(),
                r = d.optionDefaultValues.PatientInfoFieldsDefaultConfig,
                n = angular.copy(r);
            return d.getOfficeOption(d.optionKeys.PatientInfoFieldsConfig).then(function(i) {
                if (i) {
                    var r = JSON.parse(i);
                    n.forEach(function(n) {
                        var t = _.find(r, {
                            name: n.name
                        });
                        t && (n.isEnabled = t.isEnabled, n.isRequired = t.isRequired, n.isTempPatientRequired = typeof t.isTempPatientRequired == "undefined" ? n.isRequired : t.isTempPatientRequired)
                    });
                    yt(n);
                    t.resolve()
                } else rt.getSystemConfigByType("PatientRequired").success(function(i) {
                    angular.forEach(i, function(t) {
                        var i = _.find(n, {
                            name: t.configName
                        });
                        i && (i.isRequired = t.configValue.toUpperCase() == "TRUE", i.isTempPatientRequired = t.configValue.toUpperCase() == "TRUE")
                    });
                    yt(n);
                    t.resolve()
                })
            }), t.promise
        },
        at = function(n, t) {
            return moment(t, n, !0).isValid()
        },
        vt = function(n, t) {
            var i = moment(t, "YYYY-MM-DD", !0);
            return _.isString(n) && (n = momenet(n, "YYYY-MM-DD").toDate()), n = n || new Date, i.isValid() && i.toDate() <= n
        },
        yt = function(n) {
            var i = {};
            n.forEach(function(n) {
                i[n.name] = {
                    isEnabled: n.isEnabled,
                    isRequired: n.isRequired,
                    isTempPatientRequired: n.isTempPatientRequired
                }
            });
            t.verifyPatientFieldInfoDict = i
        },
        li = function(n, r) {
            var h = "isRequired",
                e, s, u, o;
            t.patient.patientType == "临时" && (h = "isTempPatientRequired");
            var f = i.defer(),
                c = r.mobile && r.mobile[h],
                l = r.phoneNumber && r.phoneNumber[h];
            for (u = 0; u < t.patient.mobileList.length; u++) {
                if (e = t.patient.mobileList[u], s = t.patient.mobileList[u - 1], e.mobile && (!/^1[0-9\*]{10}$/.test(e.mobile) || e.mobile.length != 11)) return f.reject("请填写正确的手机号码" + (u + 1) + "！"), t.focusRequiredItem("mobile" + u), f.promise;
                if (u == 0) {
                    if (c) {
                        if (!e.mobile) return f.reject("请填写号码" + (u + 1) + "的手机号码！"), t.focusRequiredItem("mobile" + u), f.promise
                    } else e.mobile || u == 0 || t.patient.mobileList.splice(u, 1);
                    if (e.mobile && !e.mobileType) return f.reject("请选择号码" + (u + 1) + "的手机号码属性！"), t.focusRequiredItem("mobile" + u), f.promise
                } else {
                    if (e.mobile && !e.mobileType) return f.reject("请选择号码" + (u + 1) + "的手机号码属性！"), t.focusRequiredItem("mobile" + u), f.promise;
                    if (s.mobile == e.mobile && s.mobile && e.mobile && s.mobileType == "本人" && e.mobileType == "本人") return f.reject("本人手机必须唯一"), t.focusRequiredItem("mobile" + u), f.promise;
                    if (c) {
                        if (!e.mobile) return f.reject("请填写号码" + (u + 1) + "的手机号码或者删除号码" + (u + 1) + "！"), t.focusRequiredItem("mobile" + u), f.promise
                    } else e.mobile || u == 0 || t.patient.mobileList.splice(u, 1)
                }
            }
            for (u = 0; u < t.patient.phoneNumberList.length; u++) {
                if (o = t.patient.phoneNumberList[u], o.mobile && !o.mobileType) return f.reject("请选择号码" + (u + 1) + "的电话号码属性！"), t.focusRequiredItem("phoneNumber" + u), f.promise;
                if (l) {
                    if (!o.mobile) return t.focusRequiredItem("phoneNumber" + u), u == 0 ? f.reject("请填写号码" + (u + 1) + "的电话号码！") : f.reject("请填写号码" + (u + 1) + "的电话号码或者删除号码" + (u + 1) + "！"), f.promise
                } else o.mobile || u == 0 || t.patient.phoneNumberList.splice(u, 1)
            }
            return v.checkPhoneNumber(t.patient.phoneNumberList).then(function() {
                f.resolve()
            }), f.promise
        },
        ai = function(n, r) {
            var u = i.defer(),
                f = "isRequired",
                e = "isEnabled";
            return t.patient.patientType == "临时" && (f = "isTempPatientRequired"), n.name ? n.patientType ? n.privateId ? r.birthDay && r.birthDay[e] && r.birthDay[f] && !n.birth ? (t.focusRequiredItem("birthDay"), u.reject("请选择生日")) : n.birth && !at("YYYY-MM-DD", n.birth) ? (t.focusRequiredItem("birthDay"), u.reject("请输入正确的生日日期")) : n.birth && !vt(new Date, n.birth) ? (t.focusRequiredItem("birthDay"), u.reject("生日日期超过允许日最大日期")) : r.age && r.age[e] && r.age[f] && !n.birth ? (t.focusRequiredItem("age"), u.reject("请输入年龄")) : r.sex && r.sex[e] && r.sex[f] && !n.sex ? (t.focusRequiredItem("sex"), u.reject("请选择性别")) : r.nickName && r.nickName[e] && r.nickName[f] && !n.nickName ? (t.focusRequiredItem("nickName"), u.reject("请输入昵称")) : r.nationality && r.nationality[e] && r.nationality[f] && !n.nationality ? (t.focusRequiredItem("nationality"), u.reject("请选择国籍")) : r.identityCard && r.identityCard[e] && r.identityCard[f] && !n.identityCard && n.birth && moment(n.birth).toDate().getAge() >= 18 ? (t.focusRequiredItem("identityCard"), u.reject("请输入身份证号")) : n.identityCard && !/(^[1|5|7][0-9]{6}\(\w{1}\)$)|(^((\s?[A-Za-z])|([A-Za-z]{2}))\d{6}(\(\w{1}\)|\w{1})$)|(^\d{8}$)|(^\d{10}$)|(^\d{15}$)|(^\d{17}(\d|x|X)$)|(^\d{4}\*+\d{3}(\d|x|X)$)/.test(n.identityCard) ? (t.focusRequiredItem("identityCard"), u.reject("请输入正确的身份证号码！")) : r.nation && r.nation[e] && r.nation[f] && !n.extension.nation ? (t.focusRequiredItem("nation"), u.reject("请输入民族")) : r.bloodType && r.bloodType[e] && r.bloodType[f] && !n.extension.bloodType ? (t.focusRequiredItem("bloodType"), u.reject("请输入血型")) : r.nativePlace && r.nativePlace[e] && r.nativePlace[f] && !n.extension.nativePlace ? (t.focusRequiredItem("nativePlace"), u.reject("请输入籍贯")) : r.marriage && r.marriage[e] && r.marriage[f] && !n.extension.marriage ? (t.focusRequiredItem("marriage"), u.reject("请选择婚姻状况")) : r.job && r.job[e] && r.job[f] && !n.extension.job ? (t.focusRequiredItem("job"), u.reject("请输入职业")) : r.religion && r.religion[e] && r.religion[f] && !n.extension.religion ? (t.focusRequiredItem("religion"), u.reject("请输入宗教信仰")) : (!n.guardian || !n.guardian.name) && t.age && t.age < 18 && r.guardian[e] && r.guardian[f] ? (t.focusRequiredItem("guardian"), u.reject("请输入监护人")) : r.passportNo && r.passportNo[e] && r.passportNo[f] && !n.extension.passportNo ? (t.focusRequiredItem("passportNo"), u.reject("请输入其他证件号")) : r.educationLevel && r.educationLevel[e] && r.educationLevel[f] && !n.extension.educationLevel ? (t.focusRequiredItem("educationLevel"), u.reject("请选择文化程度")) : r.notes && r.notes[e] && r.notes[f] && !n.notes ? (t.focusRequiredItem("notes"), u.reject("请输入患者备注")) : r.patientIcon && r.patientIcon[e] && r.patientIcon[f] && !n.pictureId ? u.reject("请选择患者头像") : r.idCardIssuer && r.idCardIssuer[e] && r.idCardIssuer[f] && !n.extension.idCardIssuer ? u.reject("发证机关不能为空") : r.idCardValidTo && r.idCardValidTo[e] && r.idCardValidTo[f] && !n.extension.idCardValidTo ? u.reject("有效期不能为空") : u.resolve() : (t.focusRequiredItem("privateId"), u.reject("请输入病历号")) : (t.focusRequiredItem("patientType"), u.reject("请选择患者类型")) : (t.focusRequiredItem("patientName"), u.reject("请输入患者姓名")), u.promise
        },
        vi = function(n, r) {
            return li(n, r).then(function() {
                return hi(), g.checkTelePhoneNumber(t.patient.telephoneNumberList).then(function(n) {
                    var r = n.data,
                        t = i.defer();
                    return r ? t.resolve() : t.reject("本人手机必须唯一！"), t.promise
                })
            }).then(function() {
                var u = i.defer(),
                    o = "isRequired",
                    f, e;
                return t.patient.patientType == "临时" && (o = "isTempPatientRequired"), r.qq && r.qq[o] && !n.qq ? (t.focusRequiredItem("qq"), u.reject("请输入QQ号")) : r.email && r.email[o] && !n.email ? (t.focusRequiredItem("email"), u.reject("请输入邮箱")) : n.email && !/\w[-\*\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/.test(n.email) ? (t.focusRequiredItem("email"), u.reject("请输入正确的邮箱！")) : r.homeAddress && r.homeAddress[o] ? (f = !1, e = "", n.familyAddress && n.familyAddress.province ? n.familyAddress.city ? n.familyAddress.district ? n.familyAddress.content || (f = !0, e = "homeAddress") : (f = !0, e = "district") : (f = !0, e = "city") : (f = !0, e = "province"), f ? (t.focusRequiredItem(e), u.reject("请填写完整的家庭住址信息！")) : u.resolve()) : u.resolve(), u.promise
            })
        },
        yi = function(n, r) {
            var u = i.defer(),
                f = "isRequired";
            return t.patient.patientType == "临时" && (f = "isTempPatientRequired"), r.sourceType && r.sourceType[f] && !n.sourceTypeLevel1 ? (t.focusRequiredItem("parentSourceType"), u.reject("患者来源为必填项！")) : n.sourceTypeLevel1 && !n.sourceType ? (t.focusRequiredItem("sourceType"), u.reject("请选择二级患者来源!")) : r.tags && r.tags[f] && n.patientTagUseList.length == 0 ? (t.focusRequiredItem("patient-used-tags"), u.reject("请选择患者标签!")) : u.resolve(), u.promise
        },
        pi = function() {
            var n = i.defer();
            return c.patientFreeFieldConfigDic.load().then(i => {
                var r, u, f;
                for (i && i.length != 0 || n.resolve(), r = i.filter(function(n) {
                        return n.isRequired && n.isInUse
                    }), r && r.length != 0 || n.resolve(), u = 0; u < r.length; u++) f = r[u].fieldCode, t.patientFreeField[f] || n.reject("自由项 " + r[u].fieldName + " 不能为空");
                n.resolve()
            }), n.promise
        },
        wi = function() {
            var i = t.verifyPatientFieldInfoDict,
                n = t.patient;
            return ai(n, i).then(function() {
                return vi(n, i)
            }).then(function() {
                return yi(n, i)
            }).then(function() {
                return pi(n)
            })
        },
        bi = function() {
            var r = i.defer(),
                u = "isRequired",
                n, f;
            return t.patient.patientType == "临时" && (u = "isTempPatientRequired"), n = t.verifyPatientFieldInfoDict, f = t.patient, n.dutyDoctorId && n.dutyDoctorId[u] && !f.dutyDoctorId ? (t.focusRequiredItem("dutyDoctorId"), r.reject("请选择责任医生")) : n.onlineConsultantId && n.onlineConsultantId[u] && !f.extension.onlineConsultantId ? (t.focusRequiredItem("onlineConsultantId"), r.reject("请选择网电咨询师")) : n.attendantId && n.attendantId[u] && !f.attendantId ? (t.focusRequiredItem("attendantId", "专属客服"), r.reject("请选择专属客服")) : r.resolve(), r.promise
        },
        ki = function() {
            var n = i.defer();
            return n.resolve(), n.promise
        },
        di = function() {
            var r = i.defer(),
                f = "isRequired",
                u, n;
            return t.patient.patientType == "临时" && (f = "isTempPatientRequired"), u = t.verifyPatientFieldInfoDict, n = t.patient, u.firstVisit && u.firstVisit[f] && !n.firstVisit ? (t.focusRequiredItem("firstVisit"), r.reject("请选择初诊日期")) : n.firstVisit && !at("YYYY-MM-DD", n.firstVisit) ? (t.focusRequiredItem("firstVisit"), r.reject("请输入正确的初诊日期")) : n.firstVisit && !vt(new Date, n.firstVisit) ? (t.focusRequiredItem("firstVisit"), r.reject("初诊日期超过允许日最大日期")) : u.doctorId && u.doctorId[f] && !n.doctorId ? (t.focusRequiredItem("doctorId"), r.reject("请选择初诊医生")) : r.resolve(), r.promise
        },
        gi = function(n) {
            var t = null;
            switch (n) {
                case "infoBase":
                    t = wi();
                    break;
                case "infoFirstVisit":
                    t = di();
                    break;
                case "infoExamination":
                    t = ki();
                    break;
                case "infoClientRelation":
                    t = bi();
                    break;
                default:
                    t = function() {
                        var n = i.defer();
                        return n.reject(), n.promise
                    }
            }
            return t
        },
        ot = function(n, i) {
            t.isShowPatientContact = a.isTenantAdmin || !a.isPatientContactTempAllowed;
            o.publish(o.events.PatientChanged, n, "PatientInfoRecordCtrl");
            t.onCleanBlockEditing(i, !0);
            w.success("保存成功");
            lt()
        },
        nr = function(n) {
            return pt(n).then(function() {}).then(function() {
                return et()
            }).then(function() {
                ot(t.patient, n)
            })
        },
        tr = function(n) {
            return pt(n).then(function() {
                var n = t.patient.bodycheck;
                return n.patientId = t.patient.id, n.disease = n.disease || "", n.medicine = n.medicine || "", n.medicineNow = n.medicineNow || "", n.id ? g.updateBodyCheck(n) : g.createBodyCheck(n)
            }).then(function() {
                return c.medicineDic.refresh(), c.medicineNowDic.refresh(), c.diseaseDic.refresh(), et()
            }).then(function() {
                ot(t.patient, n)
            })
        },
        ir = function(n) {
            return g.savePatientExtraSource(t.patient.patientExtraSources).then(function() {}).then(function() {
                return et()
            }).then(function() {
                ot(t.patient, n)
            })
        },
        rr = function() {
            for (var r, i = !1, n = 1; n <= s.FreeFieldMaxCount.Default; n++)
                if (r = "field" + n, t.patientFreeField && t.patientFreeField[r] !== undefined) {
                    i = !0;
                    break
                }
            return i
        },
        pt = function(n) {
            var r = i.defer();
            return gi(n).then(function() {
                return g.updatePatient(t.patient).then(function(n) {
                    var i = n.data;
                    if (!i) {
                        l.warn("提示", "身份证已存在！");
                        return
                    }
                    rr() ? ut.saveFreeField(t.patientFreeField).success(function(n) {
                        t.patientFreeField = n;
                        r.resolve(i)
                    }) : r.resolve(i)
                }, function(n) {
                    var t = n.data;
                    angular.isObject(t) && t.name === "PrivateIdNotUniqueException" && l.warn("提示", "病历号已经被使用！")
                })
            }, function(n) {
                angular.isString(n) && w.error(n)
            }), r.promise
        },
        ur = function(n, i, r) {
            r != "PatientInfoRecordCtrl" && r != "PatientImageCtrl" && r != "readIdentityInfo" && t.patient && (t.patient.id == i.id || t.patient.id == i.patientId) && et()
        };
    (function() {
        t.updateActiveTabTags = lt;
        t.isShowPatientContact = a.isTenantAdmin || !a.isPatientContactTempAllowed;
        t.isShowViewContactButton = a.isPatientContactTempAllowed;
        t.isShowViewLogButton = a.isTenantAdmin || a.roleType == "诊所管理员";
        t.initPatientRelation = ct;
        t.initVerifyPatientFieldInfo = ci;
        t.onSaveFinished = ot;
        t.initPatient = et;
        t.onSavePatient = nr;
        t.onSaveBodycheck = tr;
        t.onSavePatientExtraSource = ir;
        t.initPatientTagUseList = st;
        t.refreshPrivateId = oi;
        t.changePatientType = si;
        t.isPatientExtraSourceEnabled = ft.isPatientExtraSourceEnabled();
        t.$on("bind-weixin", function(n, i) {
            t.patient.marketCenterAccount = i
        });
        t.$on("guardian-dto", function(n, i) {
            i && t.patient && i.name && (t.patient.guardian = i)
        });
        o.subscribe(t, o.events.PatientChanged, ur)
    })()
}]);
patientModule.controller("PatientPrintHistoryCtrl", ["$log", "$q", "$scope", "$modal", "$modalInstance", "$filter", "loginContext", "practiceSvc", "officeSvc", "appointmentSvc", "dataDicSvc", "host", "chargeSvc", function(n, t, i, r, u, f, e, o, s, h, c, l, a) {
    "use strict";
    i.searchCriteria = {};
    i.cancel = function() {
        u.close(!0)
    };
    var b = function() {
            y();
            var n = {
                officeId: e.officeId,
                patientId: i.patient.id,
                isCancelled: !1
            };
            h.getPatientAppts(i.patient.id).success(function(n) {
                if (i.historyAppts = n.length > 0 ? n : null, i.historyAppts != null) {
                    for (var t = 0; t < i.historyAppts.length; ++t) i.historyAppts[t].startTime = moment(i.historyAppts[t].startTime).format("YYYY年MM月DD日 HH:mm");
                    a.getChargeOrdersByRange(i.searchCriteria).success(function(n) {
                        p(n);
                        v(n);
                        i.chargeorders = n
                    })
                }
            })
        },
        k = function() {
            var n = Ares.today(),
                t = moment(n).add(-6, "month").format("YYYY-MM-DD"),
                r = moment(n).format("YYYY-MM-DD"),
                u = {
                    startDate: t,
                    endDate: r
                };
            i.timeSpan = _.clone(u)
        },
        y = function() {
            i.queryByTimespan ? (i.searchCriteria.patientId = i.patient.id || null, i.searchCriteria.startPayDateTime = i.timeSpan.startDate || null, i.searchCriteria.endPayDateTime = i.timeSpan.endDate || null) : (i.searchCriteria.patientId = i.patient.id || null, i.searchCriteria.startPayDateTime = null, i.searchCriteria.endPayDateTime = null)
        },
        d = function() {
            i.queryByTimespan = !i.queryByTimespan
        },
        v = function(n) {
            var o = {},
                h = [],
                a = [],
                v = [],
                t, l, y, r, f, u, e;
            if (n != null)
                for (t = 0; t < n.length; t++) {
                    var s = n[t].id,
                        c = n[t].visitTime,
                        k = {
                            chargeOrderId: s,
                            visitTime: c
                        };
                    if (v.push(k), l = [], $(n[t].chargeOrderDetailList).each(function(n, t) {
                            t.totalPrice > 0 && l.push(t)
                        }), y = {
                            chargeOrdersId: s,
                            finalPrice: n[t].finalPrice,
                            actualPrice: n[t].actualPrice,
                            overdue: n[t].overdue
                        }, a.push(y), r = l, f = n[t].chargeOrderSimpleDetailList, r != null && r.length > 0)
                        for (u = 0; u < r.length; u++) {
                            var d = r[u].itemName,
                                g = Ares.priceToFixed(r[u].price) * 1,
                                nt = r[u].count,
                                p = Ares.priceToFixed(r[u].price * r[u].count) * 1,
                                w = Ares.priceToFixed(r[u].planPrice) * 1,
                                b = {
                                    chargeOrdersId: s,
                                    checkInDate: c,
                                    itemName: d,
                                    price: g,
                                    count: nt,
                                    actualPrice: p,
                                    discountPrice: w
                                };
                            h.push(b)
                        } else if (f != null)
                            for (e = 0; e < f.length; e++) {
                                var tt = f[e].chargeType,
                                    p = Ares.priceToFixed(f[e].totalPrice) * 1,
                                    w = Ares.priceToFixed(f[e].originalTotalPrice) * 1,
                                    b = {
                                        chargeOrdersId: s,
                                        checkInDate: c,
                                        itemName: tt,
                                        price: "",
                                        count: "",
                                        actualPrice: p,
                                        discountPrice: w
                                    };
                                h.push(b)
                            }
                }
            o.patientName = i.patient.name;
            o.privateId = i.patient.privateId;
            o.totalPriceList = a;
            o.detailList = h;
            i.chargeOrder = o;
            i.visitTimeList = v
        },
        p = function(n) {
            var t, r;
            for (_.each(n, function(n) {
                    n.finalPrice = n.planPrice - n.discountPrice;
                    n.payDateTime = moment(n.payDateTime).format("YYYY年MM月DD日 HH:mm:ss");
                    n.orderType = f("toOrderTypeString")(n.orderType);
                    n.payTypeStr = n.payType;
                    n.payType2 != "" && n.payType2 != null && (n.payTypeStr = n.payTypeStr + "," + n.payType2);
                    n.payType3 != "" && n.payType3 != null && (n.payTypeStr = n.payTypeStr + "," + n.payType3);
                    var t = c.officeDic.getItemSync(n.payOfficeId);
                    n.officeName = t.abbreviation ? t.abbreviation : t.name;
                    n.isOldCharge == !1 && (n.actualPrice = n.planPrice - n.overdue - n.discountPrice);
                    n.feeType == 1 && n.isOldCharge == !1 && (n.actualPrice = 0)
                }), t = 0; t < n.length; t++)
                if (i.historyAppts)
                    for (r = 0; r < i.historyAppts.length; ++r)
                        if (i.historyAppts[r].id == n[t].appointmentId) {
                            n[t].visitTime = i.historyAppts[r].startTime;
                            break
                        }
        },
        g = function() {
            y();
            var n = {
                officeId: e.officeId,
                patientId: i.patient.id,
                isCancelled: !1
            };
            h.getPatientAppts(i.patient.id).success(function(n) {
                if (i.historyAppts = n.length > 0 ? n : null, i.historyAppts != null) {
                    for (var t = 0; t < i.historyAppts.length; ++t) i.historyAppts[t].startTime = moment(i.historyAppts[t].startTime).format("YYYY年MM月DD日 HH:mm");
                    a.getChargeOrdersVisitTimeByRange(i.searchCriteria).success(function(n) {
                        p(n);
                        v(n);
                        i.chargeorders = n
                    })
                }
            })
        },
        nt = function(n) {
            var r = t.defer();
            return a.getChargeOrderHistoryInfoByIds(n).success(function(n) {
                angular.element(n).each(function(n, t) {
                    t.sourceChargeOrder.feeTypeStr = w(t.sourceChargeOrder.feeType);
                    angular.element(t.childChargeOrders).each(function(n, t) {
                        t.feeTypeStr = w(t.feeType)
                    })
                });
                angular.element(n).each(function(n, t) {
                    t.sourceChargeOrder.isSourceChargeOrder = !0;
                    t.childChargeOrders.unshift(t.sourceChargeOrder)
                });
                angular.element(i.visitTimeList).each(function(t, i) {
                    for (var r = 0; r < n.length; r++) i.chargeOrderId == n[r].sourceChargeOrder.id && (n[r].visitTime = i.visitTime, angular.element(n[r].childChargeOrders).each(function(t, i) {
                        i.visitTime = n[r].visitTime
                    }))
                });
                r.resolve(n)
            }), r.promise
        },
        w = function(n) {
            var t = "收费";
            switch (n) {
                case 0:
                    t = "收费";
                    break;
                case 2:
                    t = "还欠费";
                    break;
                case 1:
                case 3:
                    t = "退费"
            }
            return t
        },
        tt = function() {
            var n = null;
            return i.templateType === "A4HistoryTemplateDetail" && (n = "打印历史账单明细"), i.templateType === "A4HistoryTemplateRecord" && (n = "打印历史账单记录"), n
        };
    (function() {
        i.addChargeOrderIds = [];
        i.chargeorders = [];
        i.patient = l.patient;
        i.templateType = "A4HistoryTemplate" + l.type;
        i.title = tt();
        i.queryByTimespan = !0;
        k();
        i.query = g;
        i.formatChargeOrderDetail = v;
        i.toggleQuery = d;
        i.getChargeOrderHistoryInfoByIds = nt;
        s.getOfficeSetting().success(function(n) {
            i.officeSetting = n;
            angular.forEach(i.officeSetting.systemConfigs, function(n) {
                n.configName == "ApplyCDTCharge" && (i.isCdtMode = n.configValue.toUpperCase() == "TRUE" ? !0 : !1)
            })
        });
        o.getOffice(e.officeId).success(function(n) {
            i.office = n
        });
        b()
    })()
}]);
patientModule.controller("PatientRecordCtrl", ["$log", "$scope", "$q", "$modal", "$timeout", "$filter", "appNav", "eventAggregator", "enums", "constants", "patientSvc", "dataDicSvc", "membershipSvc", "aresDialog", "loginContext", "providerSvc", "patientUtil", "reportSvc", "practiceSvc", "aresNotification", "$rootScope", "conversationSvc", "patientTabManager", "officeOptionSvc", "permissionProvider", "systemConfigUtil", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w, b, k, d, g, nt, tt, it) {
    "use strict";
    var rt = 0,
        yt = function(n) {
            t.patient.sex = n
        },
        pt = function() {
            t.isEditMode = !0;
            t.isCreateMode = !1
        },
        wt = function() {
            t.isEditMode = !1;
            t.isCreateMode = !1;
            t.$parent.switchState("patient.record")
        },
        bt = function(n) {
            u(function() {
                t.refereePatient = n;
                t.patient.refereeName = n.name;
                t.patient.refereeId = n.id;
                t.patient.refereeMobileOrCode = n.mobile
            })
        },
        kt = function() {
            t.patient.refereeName && t.refereePatient && t.refereePatient.name == t.patient.refereeName || st()
        },
        st = function() {
            u(function() {
                t.refereePatient = null;
                t.patient.refereeId = 0;
                t.patient.refereeName = "";
                t.patient.refereeMobileOrCode = ""
            })
        },
        dt = function() {
            var f, r, u, n, i;
            for (t.patient.mobile = t.mobileList[0].mobile, t.patient.phoneNumber = t.phoneNumberList[0].mobile, f = /^(13[0-9\*]{9})|(19[0-9\*]{9})|(18[0-9\*]{9})|(14[0-9\*]{9})|(17[0-9\*]{9})|(15[0-9\*]{9})|(166[0-9\*]{8})$/, n = 0; n < t.mobileList.length; n++) {
                if (t.mobileList[n].mobile != "" && (!f.test(t.mobileList[n].mobile) || t.mobileList[n].mobile.length != 11)) {
                    t.showErrorNotification("请填写正确的手机号码" + (n + 1) + "！");
                    return
                }
                if (n == 0) {
                    if (t.requiredMobile) {
                        if (t.mobileList[n].mobile == "") {
                            t.showErrorNotification("请填写号码" + (n + 1) + "的手机号码！");
                            return
                        }
                    } else t.mobileList[n].mobile == "" && n != 0 && t.mobileList.splice(n, 1);
                    if (t.mobileList[n].mobile != "" && (t.mobileList[n].mobileType == "" || t.mobileList[n].mobileType == null)) {
                        t.showErrorNotification("请选择号码" + (n + 1) + "的手机号码属性！");
                        return
                    }
                } else {
                    if (t.mobileList[n].mobile != "" && (t.mobileList[n].mobileType == "" || t.mobileList[n].mobileType == null)) {
                        t.showErrorNotification("请选择号码" + (n + 1) + "的手机号码属性！");
                        return
                    }
                    if (t.mobileList[n - 1].mobile == t.mobileList[n].mobile && t.mobileList[n - 1].mobile != "" && t.mobileList[n].mobile != "" && t.mobileList[n - 1].mobileType == "本人" && t.mobileList[n].mobileType == "本人") {
                        t.showErrorNotification("本人手机必须唯一");
                        return
                    }
                    if (t.requiredMobile) {
                        if (t.mobileList[n].mobile == "") {
                            t.showErrorNotification("请填写号码" + (n + 1) + "的手机号码或者删除号码" + (n + 1) + "！");
                            return
                        }
                    } else t.mobileList[n].mobile == "" && n != 0 && t.mobileList.splice(n, 1)
                }
            }
            for (n = 0; n < t.phoneNumberList.length; n++) {
                if (t.phoneNumberList[n].mobile != "" && (t.phoneNumberList[n].mobileType == "" || t.phoneNumberList[n].mobileType == null)) {
                    t.showErrorNotification("请选择号码" + (n + 1) + "的电话号码属性！");
                    return
                }
                if (t.requiredPhoneNumber) {
                    if (t.phoneNumberList[n].mobile == "") {
                        if (n == 0) {
                            t.showErrorNotification("请填写号码" + (n + 1) + "的电话号码！");
                            return
                        }
                        t.showErrorNotification("请填写号码" + (n + 1) + "的电话号码或者删除号码" + (n + 1) + "！");
                        return
                    }
                } else t.phoneNumberList[n].mobile == "" && n != 0 && t.phoneNumberList.splice(n, 1)
            }
            for (t.telePhoneNumber = angular.copy(t.mobileList), n = 0; n < t.phoneNumberList.length; n++) t.telePhoneNumber.push(t.phoneNumberList[n]);
            if (t.patient.tag) {
                for (t.patientTabManager = tt, r = t.patient.tag, u = [], n = 0; n < r.length; n++) u.push({
                    tagId: r[n]
                });
                t.patient.patientTagUseList = u
            } else t.patient.patientTagUseList = null;
            if (gt(t.patient.tag), t.patient.pictureId = t.picture.id, t.patient.privateId == null || t.patient.privateId == "") {
                v.warn("提示", "病历号不能为空！");
                return
            }
            if (t.patient.refereeName || st(), t.requiredSourceType && !t.patient.hasParentSource) {
                t.showErrorNotification("患者来源为必填项！");
                return
            }
            if (t.patient.hasParentSource && !t.patient.sourceType) {
                t.showErrorNotification("请选择二级患者来源！");
                return
            }
            if (t.validateList.onlineConsultantId.required && (!t.patient.extension.onlineConsultantId || t.patient.extension.onlineConsultantId == "")) {
                t.showErrorNotification("请选择网电咨询师！");
                return
            }
            if (t.patient.familyAddress || (t.patient.familyAddress = {}), t.patient.familyAddress.content = t.patient.homeAddress, t.validateList.homeAddress.required && (!t.patient.familyAddress.province || t.patient.familyAddress.province == "" || !t.patient.familyAddress.city || t.patient.familyAddress.city == "" || !t.patient.familyAddress.district || t.patient.familyAddress.district == "" || !t.patient.familyAddress.content || t.patient.familyAddress.content == "")) {
                t.showErrorNotification("请填写完整的家庭住址信息！");
                return
            }
            if (i = tr("guardian"), i && i.isEnabled && i.isRequired && t.patient.birth && moment(t.patient.birth).toDate().getAge() < 18 && !t.patient.guardian.name) {
                t.showErrorNotification("监护人必填！");
                return
            }
            c.checkTelePhoneNumber(t.telePhoneNumber).success(function(n) {
                if (n) {
                    t.patient.telephoneNumberList = t.telePhoneNumber;
                    t.patient.familyAddress.content = t.patient.homeAddress;
                    c.updatePatient(t.patient).success(function(n) {
                        if (!n) {
                            v.warn("提示", "身份证已存在！");
                            return
                        }
                        t.patient = n;
                        l.otherSourceTypeDic.refresh();
                        t.$parent.switchState("patient.record")
                    }).error(function(n) {
                        n.name === "PrivateIdNotUniqueException" && v.warn("提示", "病历号已经被使用！")
                    });
                    var i = !1;
                    c.getBodyCheck(t.patientId).success(function(n) {
                        n != null ? (i = !1, t.bodycheck.id = n.id, ht(i)) : (i = !0, ht(i))
                    })
                } else t.showErrorNotification("本人手机必须唯一")
            })
        },
        gt = function(n) {
            if (tt && tt.activeTab && tt.activeTab.patient) {
                var i = [];
                angular.forEach(n, function(n) {
                    var r = _.find(t.patientTag, {
                        id: n
                    });
                    r && (r.title = r.isHidden ? "" : r.itemName, r.firstLetter = r.abbreviation ? r.abbreviation : r.itemName.substring(0, 1), i.push(r))
                });
                tt.activeTab.patient.tags = i
            }
        },
        ht = function(n) {
            n ? (t.bodycheck.patientId = rt, c.createBodyCheck(t.bodycheck).success(function(n) {
                t.patient.medicine = n.medicine;
                et(t.patientId);
                l.medicineDic.refresh();
                l.medicineNowDic.refresh();
                l.diseaseDic.refresh();
                l.systemsettingDic.clearCache();
                ct(t.patient)
            })) : (t.bodycheck.patientId = rt, c.updateBodyCheck(t.bodycheck).success(function(n) {
                t.bodycheck = n;
                t.patient.medicine = t.bodycheck.medicine;
                et(t.patientId);
                l.medicineDic.refresh();
                l.medicineNowDic.refresh();
                l.diseaseDic.refresh();
                l.systemsettingDic.clearCache();
                ct(t.patient)
            }))
        },
        ct = function(n) {
            o.publish(o.events.PatientChanged, n, "PatientRecordCtrl")
        },
        ut = function() {
            l.patientTagDic.load().then(function(n) {
                n = _.filter(n, function(n) {
                    return n.isInactive == !1
                });
                t.patientTag = n;
                c.getPatient(t.patientId).success(function(i) {
                    var f, e, r, u, s;
                    if (i.patientTagUseList) {
                        for (f = [], e = [], r = 0; r < i.patientTagUseList.length; r++) {
                            if (t.patientTag)
                                for (u = 0; u < t.patientTag.length; u++) i.patientTagUseList[r].tagId == t.patientTag[u].id && (s = _.any(n, function(n) {
                                    return n.id == t.patientTag[u].id && n.isInactive == !1
                                }), s && f.push(t.patientTag[u]));
                            e[r] = i.patientTagUseList[r].tagId
                        }
                        i.tag = e;
                        angular.forEach(f, function(n) {
                            !n.abbreviation && n.itemName && (n.abbreviation = n.itemName.substring(0, 1))
                        });
                        i.tagList = _.filter(f, function(n) {
                            return n.isHidden == !1
                        });
                        i.hidenTagList = _.filter(f, function(n) {
                            return n.isHidden == !0
                        })
                    }
                    i.extension || (i.extension = {});
                    t.patient = i;
                    t.patient.refereeId > 0 && (t.refereePatient = {
                        id: t.patient.refereeId,
                        name: t.patient.refereeName,
                        mobile: t.patient.refereeMobileOrCode
                    });
                    ni(i.sourceType);
                    c.getRefereeCountByPatientId(t.patientId).success(function(n) {
                        t.refereeCount = n;
                        o.publish(o.events.PatientLoaded, i, "PatientRecordCtrl");
                        i.doctorId != null && p.getName(i.doctorId).then(function(n) {
                            n && (t.patient.doctorName = n)
                        });
                        i.dutyDoctorId != null && p.getName(i.dutyDoctorId).then(function(n) {
                            t.patient.dutyDoctorName = n
                        });
                        i.consultantId != null && p.getName(i.consultantId).then(function(n) {
                            t.patient.consultantName = n || ""
                        });
                        i.extension.onlineConsultantId != null && p.getName(i.extension.onlineConsultantId).then(function(n) {
                            t.patient.extension.onlineConsultantName = n || ""
                        });
                        i.attendantId != null && l.attendantDic.load().then(function(n) {
                            var r = _.find(n, function(n) {
                                return n.id == i.attendantId
                            });
                            t.patient.attendantName = r ? r.name : ""
                        });
                        i.id && (rt = i.id, et(i.id), ft(i.id), ti(i.id));
                        i.membershipId ? ii(i.membershipId) : ri(i.id);
                        i.pictureId != 0 && lt(i.pictureId);
                        hi()
                    })
                })
            })
        },
        ni = function(n) {
            n == s.SourceType.Friend ? (t.enableReferee = !0, t.enableProvider = !1, t.enableOtherSourceType = !1) : n == s.SourceType.Provider ? (t.enableProvider = !0, t.enableReferee = !1, t.enableOtherSourceType = !1) : n ? (t.enableReferee = !1, t.enableProvider = !1, t.enableOtherSourceType = !0) : (t.enableReferee = !1, t.enableProvider = !1, t.enableOtherSourceType = !1)
        },
        lt = function(n) {
            c.getPictureById(n).success(function(n) {
                t.picture = n
            })
        },
        ft = function(n) {
            b.GetPatientRelation(n).success(function(n) {
                for (var i = 0; i < n.length; ++i) n[i].sex = f("toSexString")(n[i].sex);
                t.patientRelation = n
            }).error(function() {})
        },
        et = function(n) {
            c.getBodyCheck(n).success(function(n) {
                var r, u, i;
                if (n) {
                    if (n.isPregnant = n.isPregnant == !0 ? "是" : "否", n.isLactation = n.isLactation == !0 ? "是" : "否", l.medicineDic.refresh(), n.medicine) {
                        for (r = n.medicine.split(","), u = [], i = 0; i < r.length; i++) u[i] = r[i];
                        l.medicineDic.load().then(function(i) {
                            for (var u = _.map(i, function(n) {
                                    return n.itemName
                                }), r = 0; r < n.medicine.length; r++) _.indexOf(u, n.medicine[r]) == -1 && n.medicine[r] != "" && i.push({
                                itemName: n.medicine[r]
                            });
                            t.medicineLists = i
                        })
                    } else l.medicineDic.load().then(function(n) {
                        t.medicineLists = n
                    });
                    t.bodycheck = n
                } else l.medicineDic.load().then(function(n) {
                    t.medicineLists = n
                }), t.bodycheck = {}
            })
        },
        ti = function(n) {
            c.getMobileByPatientId(n).success(function(i) {
                if (i.length > 0) t.mobileList = i;
                else {
                    var r = {
                        mobile: "",
                        patientId: n,
                        attributes: "mobile",
                        displayOrder: 1,
                        mobileType: "本人"
                    };
                    t.mobileList.push(r)
                }
            });
            c.getPhoneNumberByPatientId(n).success(function(i) {
                if (i.length > 0) t.phoneNumberList = i;
                else {
                    var r = {
                        mobile: "",
                        patientId: n,
                        attributes: "PhoneNumber",
                        displayOrder: 1,
                        mobileType: "家"
                    };
                    t.phoneNumberList.push(r)
                }
            })
        },
        ii = function(n) {
            a.getMembership(n).success(function(n) {
                t.isShareMember = !1;
                ot(n)
            })
        },
        ri = function(n) {
            c.getMembership(n).success(function(n) {
                n && (t.isShareMember = !0, ot(n))
            })
        },
        ot = function(n) {
            if (n) {
                var i = l.membershipTypeDic.getItemSync(n.membershipTypeId);
                n.membershipTypeName = i.name;
                t.membership = n;
                t.patient.membershipId || t.isShareMember || (t.patient.membershipId = n.id)
            }
        },
        ui = function() {
            var n = r.open({
                animation: !0,
                backdrop: "static",
                template: "<membership-card-view><\/membership-card-view>",
                controller: "MembershipCardCtrl",
                windowClass: "membership-dialog",
                size: "sm",
                resolve: {
                    host: function() {
                        return {
                            patient: t.patient
                        }
                    }
                }
            });
            n.result.then(function(n) {
                ot(n);
                o.publish(o.events.PatientChanged, t.patient, "PatientRecordCtrl")
            })
        },
        fi = function() {
            e.goToMembership(t.patient.id)
        },
        ei = function(n, i) {
            var u = r.open({
                animation: !0,
                backdrop: "static",
                template: "<patient-relation-edit-view><\/patient-relation-edit-view>",
                controller: "PatientRelationEditCtrl",
                size: "md",
                resolve: {
                    host: function() {
                        return {
                            patient: t.patient,
                            action: n || "add",
                            id: i
                        }
                    }
                }
            });
            u.result.then(function() {
                ft(t.patient.id)
            })
        },
        oi = function(n) {
            v.confirm("删除关系人", "确定要删除此关系人？").then(function() {
                c.deleteRelation(n).success(function() {
                    ft(t.patient.id)
                })
            })
        },
        si = function(n) {
            u(function() {
                var i = r.open({
                    animation: !0,
                    backdrop: "static",
                    template: "<patient-photo-view><\/patient-photo-view>",
                    controller: "PatientPhotoCtrl",
                    size: "md",
                    resolve: {
                        host: function() {
                            return {
                                patient: t.patient,
                                event: n
                            }
                        }
                    }
                });
                i.result.then(function(n) {
                    lt(n)
                })
            })
        },
        hi = function() {
            w.getAvailablePatientTypes(t.patient.patientType).then(function(n) {
                t.isPatientTypeChangable = t.patient.officeId == y.officeId ? n.length > 0 : !1
            })
        },
        ci = function() {
            w.changePatientType(t.patient).then(function() {
                e.reload()
            })
        },
        li = function() {
            o.subscribe(t, o.events.PatientChanged, at);
            t.$on("bind-weixin", function(n, i) {
                t.patient.marketCenterAccount = i
            })
        },
        ai = function() {
            o.unsubscribe(t, o.events.PatientChanged, at)
        },
        vi = function() {
            nt.unBindSaasPatient(t.patientId).success(function(n) {
                if (n) {
                    var i = t.findPatientTabManagerScope();
                    i && i.patientTabManager.activeTab && i.patientTabManager.activeTab.patient && i.patientTabManager.activeTab.patient.marketCenterAccount && (i.patientTabManager.activeTab.patient.marketCenterAccount = "");
                    t.patient.marketCenterAccount = "";
                    g.$broadcast("bind-weixin", "")
                } else d.error("解绑失败")
            }).error(function(t) {
                d.error("解绑失败");
                t.name == "ScrmException" && n.log("调用SCRM解绑接口失败");
                n.log(t)
            })
        },
        at = function(n, i, r) {
            r == "PatientCheckInCtrl" ? t.patient && t.patient.id == i.patientId && (t.patient.doctorId != i.doctorId || t.patient.consultantId != i.consultantId) && ut() : r != "PatientRecordCtrl" && t.patient && t.patient.id == i.id && ut()
        },
        yi = function() {
            g.isNewWxEnabled && pi()
        },
        pi = function() {
            c.generatePatientQrCode(t.patient.id).then(function(i) {
                var u, f;
                i ? (u = {
                    interval: 3e3,
                    delay: 100,
                    maxCount: 20,
                    bindWeiXin: !0,
                    queryFunc: ki
                }, c.sendScrmQrCode(i).success(function() {
                    n.log("scrm2.0发送二维码到智能话机成功")
                }).error(function(t) {
                    n.log(t)
                }), f = r.open({
                    animation: !0,
                    backdrop: "static",
                    template: "<qrcode-dialog><\/qrcode-dialog>",
                    controller: "QrcodeDialogCtrl",
                    size: "sm",
                    resolve: {
                        host: function() {
                            return {
                                qrCode: i,
                                outTradeNo: 1,
                                isMarketCenter: !1,
                                queryOption: u
                            }
                        }
                    }
                }), f.result.then(function() {
                    c.getPatient(t.patient.id).success(function(n) {
                        t.patient = n;
                        n && n.marketCenterAccount && d.success("微信绑定成功")
                    })
                })) : d.error("该诊所未授权微信公众号")
            })
        },
        wi = function() {
            t.$parent.switchState("marketingCenter.marketingSingleConsult")
        },
        bi = function() {
            var n = i.defer();
            return t.isShowViewContactButton = y.isPatientContactTempAllowed, t.isShowViewLogButton = y.isTenantAdmin || y.roleType == "诊所管理员", vt().then(function(i) {
                t.officeSetting = i;
                t.systemConfigs = {};
                var r = t.officeSetting;
                angular.forEach(t.officeSetting, function(n) {
                    n.name == "mobile" && n.isRequired && n.isEnabled ? t.requiredMobile = !0 : n.name == "phoneNumber" && n.isRequired && n.isEnabled && (t.requiredPhoneNumber = !0)
                });
                n.resolve(!0)
            }), n.promise
        },
        ki = function() {
            var n = i.defer();
            return c.getPatient(t.patientId).success(function(i) {
                i.marketCenterAccount && (t.patient.marketCenterAccount = i.marketCenterAccount, g.$broadcast("bind-weixin", t.patient.marketCenterAccount), n.resolve({
                    result: !0
                }))
            }), n.promise
        },
        vt = function() {
            var n = i.defer(),
                r = it.optionDefaultValues.PatientInfoFieldsDefaultConfig;
            return t.PatientInfoConfigFields = angular.copy(r), it.getOfficeOption(it.optionKeys.PatientInfoFieldsConfig).then(function(i) {
                if (i) {
                    var r = JSON.parse(i);
                    t.PatientInfoConfigFields.forEach(function(n) {
                        var t = _.find(r, {
                            name: n.name
                        });
                        t && (n.isEnabled = t.isEnabled, n.isRequired = t.isRequired)
                    });
                    n.resolve(t.PatientInfoConfigFields)
                } else k.getSystemConfigByType("PatientRequired").success(function(i) {
                    angular.forEach(i, function(n) {
                        var i = _.find(t.PatientInfoConfigFields, {
                            name: n.configName
                        });
                        i && (i.isRequired = n.configValue.toUpperCase() == "TRUE")
                    });
                    n.resolve(t.PatientInfoConfigFields)
                })
            }), n.promise
        },
        di = function() {
            var n = t.patient.id,
                i = r.open({
                    animation: !0,
                    backdrop: "static",
                    template: "<operation-log-list-view><\/operation-log-list-view>",
                    controller: "OperationLogListCtrl",
                    size: "lg",
                    windowClass: "operation-log-dialog",
                    resolve: {
                        host: function() {
                            return {
                                id: n,
                                type: "PatientContact"
                            }
                        }
                    }
                })
        },
        gi = function() {
            t.isShowPatientContact = !0;
            nr()
        },
        nr = function() {
            c.addViewPatientLog(t.patient.id, t.patient.name)
        },
        tr = function(n) {
            return _.find(t.PatientInfoConfigFields, {
                name: n
            })
        };
    (function() {
        t.picture = {};
        t.phoneNumberList = [];
        t.mobileList = [];
        t.requiredMobile = !1;
        t.requiredPhoneNumber = !1;
        t.isEditMode = !1;
        t.edit = pt;
        t.cancel = wt;
        t.save = dt;
        t.setSex = yt;
        t.openCard = ui;
        t.unBindPatientWeiXin = vi;
        t.goToMembershipDetail = fi;
        t.editRelation = ei;
        t.deleteRelations = oi;
        t.onClickFileDialog = si;
        t.changePatientType = ci;
        t.getPatientQrcode = yi;
        t.openWxConversation = wi;
        t.onRefereeSelected = bt;
        t.onLostFocused = kt;
        t.getPatientInfoFieldsConfig = vt;
        t.showContactView = gi;
        t.viewPatientContactLog = di;
        ut();
        li();
        bi();
        k.getItemTypes("mobileAttribute").success(function(n) {
            t.mobileAttribute = n
        });
        k.getItemTypes("phoneNumberAttribute").success(function(n) {
            t.phoneNumberAttribute = n
        });
        t.$on("$destroy", function() {
            ai()
        })
    })()
}]);
patientModule.controller("PatientRelationEditCtrl", ["$log", "$scope", "$modalInstance", "patientSvc", "membershipSvc", "dataDicSvc", "aresDialog", "host", "enums", function(n, t, i, r, u, f, e, o, s) {
    "use strict";
    var h = null,
        c = function() {
            t.action = o.action ? o.action : "add"
        },
        l = function() {
            t.action == "edit" ? (h = o.id, v(h)) : h = o.id
        },
        a = function(n) {
            r.getPatient(n).success(function(n) {
                t.patient = n
            })
        },
        v = function(n) {
            r.getRelatio_ById(n).success(function(n) {
                t.relation = n;
                a(n.targetId)
            })
        };
    t.relation = {};
    var y = function(n) {
            t.patient = n;
            t.relation.ownerId = o.patient.id;
            t.relation.targetId = n.id
        },
        p = function() {
            t.relation.targetType = s.PatientRelationTargetType.Patient;
            t.relation.ownerId != t.relation.targetId ? t.action == "add" ? r.getRelationById(t.relation).success(function(n) {
                n[0] != null ? e.warn("提示", "此患者已在亲友关系列表中！") : r.createRelation(t.relation).success(function() {
                    i.close(t.relation)
                })
            }) : t.action == "edit" && r.updateRelation(t.relation).success(function() {
                i.close(t.relation)
            }) : e.warn("提示", "不能将自己添加为亲友关系！")
        },
        w = function() {
            i.dismiss("cancel")
        },
        b = function() {
            c();
            l()
        };
    (function() {
        b();
        t.onPatientSelected = y;
        t.cancel = w;
        t.save = p
    })()
}]);
patientModule.controller("PatientRevisitRecordCtrl", ["$log", "$scope", "$filter", "$sce", "$modal", "revisitSvc", "enums", "patientUtil", "loginContext", "aresModalShelf", function(n, t, i, r, u, f, e, o, s, h) {
    "use strict";
    var l = i("toRevisitStateStr"),
        a = function(n) {
            var r, u, i;
            return t.isAllLevel ? !0 : t.isPersonalLevel ? (r = s.userId, u = s.providerId, r == n.recordCreatedUser || u == n.visitorId ? !0 : !1) : (i = s.department, i == n.createdUserDepartment || i == n.visitDepartment ? !0 : !1)
        },
        c = function() {
            f.getPatientRevisits(t.patientId).success(function(n) {
                angular.forEach(n, function(n) {
                    n.stateStr = l(n.state);
                    n.canEdit = a(n);
                    n.canExecute = (!n.visitorId || n.visitorId == s.providerId) && n.state == e.RevisitState.Pending.value
                });
                t.revisitList = n
            })
        },
        v = function() {
            var n = h.open({
                title: "新增回访",
                template: "<customer-revisit-edit-modal-view><\/customer-revisit-edit-modal-view>",
                controller: "CustomerRevisitEditModalCtrl",
                resolve: {
                    host: function() {
                        return {
                            patientId: t.patientId,
                            isRevisitTask: !1
                        }
                    }
                }
            });
            n.result.then(function() {
                c()
            })
        },
        y = function(n, i) {
            var r = i == e.RevisitState.Pending.value || i == e.RevisitState.Cancelled.value,
                u = h.open({
                    title: r ? "编辑回访任务" : "编辑回访",
                    template: "<customer-revisit-edit-modal-view><\/customer-revisit-edit-modal-view>",
                    controller: "CustomerRevisitEditModalCtrl",
                    resolve: {
                        host: function() {
                            return {
                                revisitId: n,
                                isRevisitTask: r,
                                patientId: t.patientId,
                                isEdit: !0
                            }
                        }
                    }
                });
            u.result.then(function() {
                c()
            })
        },
        p = function(n) {
            var i = h.open({
                title: "执行回访",
                template: "<customer-revisit-edit-modal-view><\/customer-revisit-edit-modal-view>",
                controller: "CustomerRevisitEditModalCtrl",
                resolve: {
                    host: function() {
                        return {
                            revisitId: n,
                            isRevisitTask: !1,
                            patientId: t.patientId,
                            isEdit: !0
                        }
                    }
                }
            });
            i.result.then(function() {
                c()
            })
        },
        w = function() {
            t.patientPermissionLevel = o.getPatientPermissionLevel();
            t.isAllLevel = t.patientPermissionLevel == e.PatientPermissionLevel.All;
            t.isPersonalLevel = t.patientPermissionLevel == e.PatientPermissionLevel.Personal;
            t.isDepartmentLevel = t.patientPermissionLevel == e.PatientPermissionLevel.Department
        };
    (function() {
        w();
        t.createRevisit = v;
        t.editRevisit = y;
        t.executeRevisit = p;
        c()
    })()
}]);
patientModule.controller("PatientTxplanEditCtrl", ["$log", "$scope", "$q", "$modalInstance", "membershipSvc", "aresDialog", "dataDicSvc", "host", function(n, t, i, r, u, f, e, o) {
    "use strict";
    var s = {},
        h = {},
        c = function(n) {
            var i = n[0],
                r = n[1],
                u = n[2];
            t.chargeSupCatagoryList = [];
            i.forEach(function(n) {
                t.chargeSupCatagoryList.push(n);
                s[n.id] = []
            });
            r.forEach(function(n) {
                var i = _.findIndex(t.chargeSupCatagoryList, function(t) {
                    return n.itemSuperCategoryId == t.id ? !0 : !1
                });
                i != -1 && (s[n.itemSuperCategoryId].push(n), h[n.id] = [])
            });
            u.forEach(function(n) {
                var t = s[n.itemSuperCategoryId],
                    i;
                if (t) {
                    if (i = _.findIndex(t, function(t) {
                            return n.itemCatagoryId == t.id ? !0 : !1
                        }), i == -1) return
                } else return;
                h[n.itemCatagoryId].push(n)
            });
            t.defaultSupCategoryId = t.chargeSupCatagoryList.length > 0 ? t.chargeSupCatagoryList[0].id : 0;
            t.chargeCatagoryList = s[t.defaultSupCategoryId];
            t.chargeCatagoryList && t.chargeCatagoryList.length > 0 && (t.defaultCategoryId = t.chargeCatagoryList[0].id);
            t.chargeItemList = h[t.defaultCategoryId]
        },
        l = function() {
            t.giftPlanList = [];
            t.existList && t.existList.length > 0 && _.each(t.existList, function(n) {
                t.giftPlanList.push(n)
            })
        },
        a = function() {
            r.dismiss("cancel")
        },
        v = function() {
            r.close(t.giftPlanList)
        },
        y = function(n, i) {
            t.chargeItemList = null;
            n ? t.chargeItemList = h[n] : i && (t.chargeCatagoryList = s[i], t.chargeCatagoryList && t.chargeCatagoryList.length > 0 && (t.defaultCategoryId = t.chargeCatagoryList[0].id, t.chargeItemList = h[t.defaultCategoryId]))
        };
    (function() {
        t.existList = o.giftPlanList;
        t.save = v;
        t.cancel = a;
        t.resetChargeItemList = y;
        t.chargeSupCatagoryList = null;
        t.chargeCatagoryList = null;
        t.chargeItemList = null;
        t.defaultSupCategoryId = 0;
        t.defaultCategoryId = 0;
        l();
        i.all([e.chargeSuperCategoryDic.load(), e.chargeCategoryDic.load(), e.chargeItemDic.load(), ]).then(function(n) {
            c(n)
        })
    })()
}]);
patientModule.controller("PatientTxplanCtrl", ["$scope", "$log", "$sce", "$timeout", "$modal", "aresDialog", "aresNotification", "dataDicSvc", "patientSvc", "toothUtil", "patientUtil", "formatUtil", function(n, t, i, r, u, f, e, o, s, h, c, l) {
    "use strict";
    var v = function() {
            y();
            w()
        },
        y = function() {
            s.getAllTxPlanByPatient(n.patientId).success(function(t) {
                t && (n.planingTP = [], n.confirmedTP = [], n.rejectTP = [], angular.forEach(t, function(t) {
                    t.status == 0 ? n.unplannedTP.push(t) : t.status == 1 ? n.planingTP.push(t) : t.status == 2 ? n.confirmedTP.push(t) : t.status == 3 && n.rejectTP.push(t)
                }))
            }).error(function(n) {
                t.log(n);
                t.log("获取所有计划项目出错");
                f.info("提示", "加载出错!")
            })
        },
        w = function() {
            s.getNotRelatedTxPlan(n.patientId).success(function(t) {
                t && (n.unplannedTP = t, o.txplanItemDic.load().then(function(t) {
                    angular.forEach(n.unplannedTP, function(n) {
                        var i = _.find(t, function(t) {
                            return t.id === n.transactionCodeId
                        });
                        n.transactionCodeName = i ? i.name : "";
                        b(n)
                    })
                }))
            }).error(function(n) {
                t.log(n);
                t.log("获取未关联计划项目出错");
                f.info("提示", "加载出错!")
            })
        },
        b = function(n) {
            var i = n.region.split(","),
                t = "";
            angular.forEach(i, function(i) {
                i === "MesialOcclusal" ? t += "I/O(M)," : i === "DistalOcclusal" ? t += "I/O(D)," : i === "MesialCrown" ? t += "M," : i === "DistalCrown" ? t += "D," : i === "FacialCrown" ? t += "F," : i === "LingualCrown" ? t += "L," : i === "WholeMesialRoot" ? t += "近中颊根," : i === "WholeDistalRoot" ? t += "远中颊根," : i === "WholeCenterRoot" && (t += h.isSingleRootTooth(n.toothCode) ? "牙根" : "腭根", t += ",")
            });
            t && (t = t.substr(0, t.length - 1));
            n.regionName = t
        },
        g = function(t, i) {
            if (t != 0) {
                var r = u.open({
                    animation: !0,
                    backdrop: "static",
                    controller: "PatientTxplanItemCtrl",
                    template: "<patient-txplan-item-view><\/patient-txplan-item-view>",
                    windowClass: "patient-txplan-edit-dialog",
                    resolve: {
                        host: function() {
                            return {
                                itemId: t,
                                CodeId: i
                            }
                        }
                    }
                });
                r.result.then(function(t) {
                    if (t) {
                        var i = _.find(n.txplan.txplanItemList, function(n) {
                            return n.id == t.id
                        });
                        i && (i.txplanItemChargeList = t.txplanItemChargeList, i.price = t.price, d(i.txplanItemChargeList))
                    }
                })
            }
        },
        a = function(i, r) {
            n.selectedItem = i;
            n.selectStuats = r;
            n.isSelectedAll = !1;
            s.getTxPlan(i).success(function(t) {
                t && (n.joinPlanData && n.joinPlanData.id == i && (n.joinPlanData = null), o.txplanItemDic.load().then(function(n) {
                    angular.forEach(t.txplanItemList, function(t) {
                        var i = _.find(n, function(n) {
                                return n.id === t.transactionCodeId
                            }),
                            r, u;
                        t.transactionCodeName = i ? i.name : "";
                        t.apptDate && (t.apptDateStr = moment(t.apptDate).format("YYYY-MM-DD"));
                        t.status == 1 ? (r = t.toPlannedTime ? moment(t.toPlannedTime).format("YYYY-MM-DD") : "", u = moment(new Date).format("YYYY-MM-DD"), t.statusStr = r == u ? "进行中(新增)" : "进行中") : t.status == 0 ? t.statusStr = "未计划" : t.status == 2 && (t.statusStr = "已完成");
                        b(t)
                    })
                }), n.txplan = t)
            }).error(function(n) {
                t.log(n);
                f.info("提示", "加载出错!")
            })
        },
        nt = function() {
            s.confirmedTxplan(n.txplan.id).success(function(t) {
                t && (n.listActive2 = !0, y(), a(n.txplan.id, "Confirmed"))
            }).error(function(n) {
                t.log(n);
                f.info("提示", "完成操作出错!")
            })
        },
        tt = function() {
            s.rejectTxPlan(n.txplan.id).success(function(t) {
                t && (n.listActive3 = !0, y(), a(n.txplan.id, "Reject"))
            }).error(function(n) {
                t.log(n);
                f.info("提示", "拒绝操作出错!")
            })
        },
        it = function() {
            s.againTxplan(n.txplan.id).success(function(t) {
                t && (n.listActive1 = !0, v(), a(n.txplan.id, "Planing"))
            }).error(function(n) {
                t.log(n);
                f.info("提示", "重新开始操作出错!")
            })
        },
        rt = function() {
            var i = p(!0);
            if (i && i.length > 0) {
                var r = ct(i),
                    u = (n.planingTP && n.planingTP.length) > 0 ? "治疗计划" + (n.planingTP.length + 1) : "治疗计划1",
                    e = {
                        name: u,
                        price: r,
                        status: 1,
                        patientId: n.patientId,
                        txplanItemList: i
                    };
                s.createTxPlan(e).success(function(t) {
                    t && (v(), n.listActive1 = !0)
                }).error(function(n) {
                    t.log(n);
                    f.info("提示", "保存出错!")
                })
            } else {
                f.info("提示", "请选择一条未计划的项目,您可以从牙齿检查图上添加新项目!");
                return
            }
        },
        ut = function(i) {
            var r = p(!0, i),
                u;
            if (r && r.length > 0) n.joinPlanData = {
                id: i,
                newItemCount: r.length
            }, u = {
                list: r
            }, s.addTxplanItemToTxplan(u).success(function(t) {
                t && (v(), n.listActive1 = !0)
            }).error(function(n) {
                t.log(n);
                f.info("提示", "保存出错!")
            });
            else {
                f.info("提示", "请选择一条未计划的项目,您可以从牙齿检查图上添加新项目!");
                return
            }
        },
        ft = function() {
            var t = p(!1);
            c.createTxplanAppt(n.patientId, t).then(function() {
                a(n.txplan.id, "Planing");
                f.info("消息", "预约成功")
            })
        },
        et = function(t) {
            t && (t == "Unplanned" ? n.unplannedTP && n.unplannedTP.length > 0 && (n.isSelectedAll = !n.isSelectedAll, k(n.unplannedTP)) : n.txplan && n.txplan.txplanItemList && n.txplan.txplanItemList.length > 0 && (n.isSelectedAll = !n.isSelectedAll, k(n.txplan.txplanItemList)))
        },
        k = function(t) {
            angular.forEach(t, function(t) {
                t.selected = n.isSelectedAll
            })
        },
        ot = function(n) {
            n.selected = !n.selected
        },
        st = function(n) {
            f.confirm("提示", "您确认要删除吗？").then(function() {
                s.deleteTxPlanItem(n).success(function(n) {
                    n && (w(), e.success("删除成功"))
                }).error(function(n) {
                    t.log(n);
                    f.info("提示", "删除出错!")
                })
            })
        },
        ht = function(i) {
            f.confirm("提示", "您确认要移除吗？").then(function() {
                s.removeTxPlanItem(i).success(function(t) {
                    t && (v(), a(n.txplan.id, "Planing"), e.success("移除成功"))
                }).error(function(n) {
                    t.log(n);
                    f.info("提示", "移除出错!")
                })
            })
        },
        p = function(t, i) {
            var r = [];
            return t ? (r = _.filter(n.unplannedTP, function(n) {
                return n.selected == !0
            }), r.length > 0 && i && angular.forEach(r, function(n) {
                n.txplanId = i
            })) : r = _.filter(n.txplan.txplanItemList, function(n) {
                return n.selected == !0
            }), r
        },
        pt = function(t) {
            return t && angular.forEach(n.unplannedTP, function(n) {
                n.selected = !1
            }), []
        },
        ct = function(n) {
            var t = 0;
            return angular.forEach(n, function(n) {
                t += n.price
            }), t
        },
        d = function(n) {
            o.chargeItemDic.load().then(function(t) {
                angular.forEach(n, function(n) {
                    var r = _.find(t, function(t) {
                            return t.id === n.chargeItemId
                        }),
                        u, f;
                    n.name = r ? r.itemName : "";
                    n.price = r ? r.price * n.count : 0;
                    n.remainCount == 0 ? n.statusStr = "已收费" : (u = u = '<span style="width:100%;color:#F6AA2E;">' + n.remainCount + "次未收费<\/span>", f = n.count - n.remainCount, f > 0 && (u += "<br />" + f + "次已收费"), n.statusStr = i.trustAsHtml(u))
                })
            })
        },
        lt = function(n, i) {
            n.showChargeDiv = i;
            n.showDetail = !n.showDetail;
            n.showDetail && (n.txplanItemChargeList.length > 0 && d(n.txplanItemChargeList), n.apptHistoryList || s.getHistoryTxplanItem(n.id).success(function(t) {
                t && (angular.forEach(t, function(n) {
                    l.formatAppt(n.appointment);
                    n.apptDateStr = moment(n.apptDate).format("YYYY-MM-DD");
                    n.stateStr = n.appointment.stateStr
                }), n.apptHistoryList = t)
            }).error(function(n) {
                t.log(n);
                f.info("提示", "加载预约历史出错!")
            }))
        },
        at = function(n) {
            n.showChargeDiv = !n.showChargeDiv
        },
        vt = function(i, r) {
            if (i.status != r) {
                var u = {
                    id: i.id,
                    status: r
                };
                s.updateTxplanItemStatu(u).success(function(t) {
                    t && (a(n.txplan.id, "Planing"), e.success("修改成功"))
                }).error(function(n) {
                    t.log(n);
                    f.info("提示", "修改状态出错!")
                })
            }
        },
        yt = function() {
            var i = {
                id: n.txplan.id,
                notes: n.txplan.notes
            };
            s.updateTxplanNotes(i).success(function(n) {
                n && e.success("保存成功")
            }).error(function(n) {
                t.log(n);
                f.info("提示", "保存备注出错!")
            })
        };
    (function() {
        n.selectStuats = "Unplanned";
        n.selectedItem = "Unplanned";
        n.onSelectedAll = et;
        n.onSelectedOne = ot;
        n.removeItemClick = ht;
        n.deleteItemClick = st;
        n.joinPlan = ut;
        n.isSelectedAll = !1;
        n.listActive1 = !1;
        n.listActive2 = !1;
        n.listActive3 = !1;
        n.itemClick = a;
        n.confirmedTxplan = nt;
        n.rejectTxPlan = tt;
        n.againTxplan = it;
        n.newPlan = rt;
        n.creatAppt = ft;
        n.onShowDetailClick = lt;
        n.onShowChargeClick = at;
        n.updateTxplanItemStatu = vt;
        n.updateTxplanNotes = yt;
        n.openEditDialog = g;
        v()
    })()
}]);
patientModule.controller("patientWeixinConsultCtrl", ["$log", "$scope", "$modalInstance", "appointmentConsultSvc", "patientSvc", "host", function(n, t, i, r, u, f) {
    "use strict";
    var e = function() {
            i.dismiss("cancel")
        },
        o = function() {
            u.getPatient(f.patientId).success(function(n) {
                if (n.marketCenterAccount) {
                    var i = {
                        fansId: n.marketCenterAccount
                    };
                    r.getMessagesByFansId(i).success(function(n) {
                        t.hasRecord = n.length > 0;
                        t.chatMessages = s(n)
                    })
                } else t.chatMessages = []
            })
        },
        h = function(n) {
            var t = new Date,
                n;
            return t.setTime(n), moment(t).format("YYYY-MM-DD HH:mm")
        },
        s = function(n) {
            return angular.forEach(n, function(n) {
                n.recordCreatedTime = moment(n.recordCreatedTime).format("YYYY-MM-DD HH:mm");
                n.sender = n.senderName ? n.senderName : "";
                n.target = n.targetName ? n.targetName : ""
            }), _.groupBy(n, "recordCreatedTime")
        };
    (function() {
        t.cancel = e;
        o()
    })()
}]);
patientModule.controller("PatientDentalLabOrderCtrl", ["$log", "$scope", "$q", "$state", "$timeout", "dentalLabSvc", "aresNotification", function(n, t, i, r, u, f, e) {
    "use strict";
    t.operBtnNameObj = {
        10: "提交",
        15: "取模",
        20: "签收",
        30: "验收",
        44: "结算"
    };
    var o = function() {
            var n = i.defer(),
                r = t.searchCriteria;
            return f.searchOrder(r).then(function(i) {
                t.dentalLabOrderList = s(i.data.items);
                t.dentalLabOrderTotalCount = i.data.totalCount;
                u(function() {
                    t.initTableView()
                });
                n.resolve(!0)
            }), n.promise
        },
        s = function(n) {
            return angular.forEach(n, function(n) {
                n.orderDateStr = n.submitTime ? moment(n.submitTime).format("YYYY-MM-DD") : "";
                n.orderStatusStr = t.operBtnNameObj[n.orderStatus]
            }), n
        },
        h = function(n) {
            f.submitOrder(n).success(function() {
                o()
            }).error(function() {
                e.error("提交订单到开放平台失败")
            })
        },
        c = function(n) {
            var t = i.defer();
            return f.orderAction(n).then(function() {
                o();
                t.resolve()
            }), t.promise
        };
    (function() {
        t.searchDentalLabOrder = o;
        t.patientId = r.params.patientId;
        t.toSubmit = h;
        t.orderAction = c;
        t.searchCriteria = {
            pageSize: 10,
            pageIndex: 1,
            patientId: t.patientId
        };
        o()
    })()
}]);
patientModule.controller("PatientLisorderEditCtrl", ["$log", "$scope", "$state", "dataDicSvc", "loginContext", function(n, t, i, r, u) {
    "use strict";
    (function() {
        var f, n;
        for (t.patientId = i.params.patientId, t.appointId = i.params.apptId, t.currentOrderId = i.params.orderId, t.editstatus = i.params.status, f = r.officeDic.data(), n = 0; n < f.length; ++n)
            if (f[n].id == u.officeId) {
                t.office = f[n];
                break
            }
    })()
}]);
patientModule.controller("PatientLisorderCtrl", ["$log", "$scope", "$filter", "$state", "appNav", "patientSvc", "aresDialog", "loginContext", "dataDicSvc", function(n, t, i, r, u, f, e, o, s) {
    "use strict";
    var h, c;
    t.lisOrders = [];
    h = i("toOfficeAbbr");
    t.listPatientLisOrders = function() {
        t.lisOrders = [];
        f.listLisOrdersForPatient(t.patientId).success(function(n) {
            for (var i = 0; i < n.length; i++) n[i].officeName = h(n[i].officeId);
            t.lisOrders = n.reverse()
        }).error(function() {
            t.lisOrders = []
        })
    };
    t.discardLisOrder = function(n) {
        if (n.officeId != o.officeId) {
            t.showErrorNotification("不可修改其他诊所的记录");
            return
        }
        if (n.chargeOrderStatus == "已收费") {
            t.showErrorNotification("已收费的申请单无法直接作废，如仍需作废，请让收款员先作废对应收费记录！");
            return
        }
        e.confirm("提醒", "确定要作废此医嘱？作废后不可恢复！").then(function() {
            f.discardLisOrder(n.id).success(function() {
                t.listPatientLisOrders()
            }).error(function() {
                t.showErrorNotification("无法作废！")
            })
        })
    };
    c = function() {
        u.switchState("patientLisOrder.createRecord", {
            patientId: t.patientId,
            orderId: 0,
            status: 1
        })
    };
    t.editLisOrder = function(n) {
            if (n.officeId != o.officeId) {
                t.showErrorNotification("不可修改其他诊所的记录");
                return
            }
            n.orderStatus != "未提交" ? u.switchState("patientLisOrder.createRecord", {
                patientId: t.patientId,
                orderId: n.id,
                status: 0
            }) : u.switchState("patientLisOrder.createRecord", {
                patientId: t.patientId,
                orderId: n.id,
                status: 1
            })
        },
        function() {
            t.patientId = r.params.patientId;
            t.appointId = r.params.apptId;
            f.getPatient(t.patientId).success(function(n) {
                t.patient = n
            });
            s.officeDic.load().then(function(n) {
                t.officeList = n
            });
            t.officeId = o.officeId;
            t.isRegularChain = t.$root.isRegularChain;
            t.createNewOrder = c;
            t.listPatientLisOrders()
        }()
}]);
patientModule.controller("OutprocessFixedDentureCtrl", ["$log", "$scope", "$location", "$http", "$state", "appNav", "enums", "dataDicSvc", "patientSvc", "practiceSvc", "appointmentSvc", "constants", "aresDialog", "loginContext", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v) {
    "use strict";
    var p, w, y, b;
    t.colorCodeList = {};
    t.outProcessItemList = {};
    t.supplyers = {};
    t.statuses = {};
    t.pickers = {};
    t.annexContent = ["对颌模", "蜡堤", "硅橡胶", "原牙", "研究模", "颌架"];
    t.createOutprocessOrder = function() {
        t.currentOutprocessOrder = {
            id: 0,
            appointmentId: 0,
            pId: t.patientId,
            status: "待处理",
            supplyName: "",
            pickerName: "",
            pickerPhone: "",
            processDays: 0,
            doctorName: "",
            doctorId: 0,
            customerPrice: 0,
            factoryPrice: 0,
            notes: "",
            orderNo: "",
            sendDate: moment(new Date).format("YYYY-MM-DD HH:mm:ss"),
            backDate: moment(new Date).format("YYYY-MM-DD HH:mm:ss"),
            tryDateTime: moment(new Date).format("YYYY-MM-DD HH:mm:ss"),
            orderDetailList: [],
            orderType: t.catagory
        };
        t.initOrderDetail()
    };
    t.deleteOrderDetail = function(n) {
        t.currentOutprocessOrder.orderDetailList.length > 0 && t.currentOutprocessOrder.orderDetailList.splice(n, 1)
    };
    t.initDoctor = function() {
        h.getDoctors().success(function(n) {
            var r, i;
            if ($("#doctor").kendoDropDownList({
                    dataSource: n,
                    placeholder: "请选择医生",
                    dataTextField: "name",
                    dataValueField: "id",
                    select: function(n) {
                        var i = this.dataItem(n.item.index());
                        t.currentOutprocessOrder.doctorName = i.name;
                        t.currentOutprocessOrder.doctorId = i.id;
                        t.currentOutprocessOrder.doctorPhone = i.mobile
                    }
                }), r = $("#doctor").data("kendoDropDownList"), t.currentOutprocessOrder && t.currentOutprocessOrder.doctorId) {
                for (i = 0; i < n.length; ++i)
                    if (n[i].id == t.currentOutprocessOrder.doctorId) {
                        r.select(i);
                        t.currentOutprocessOrder.doctorName = n[i].name;
                        t.currentOutprocessOrder.doctorPhone = n[i].mobile;
                        break
                    }
            } else
                for (i = 0; i < n.length; ++i)
                    if (n[i].id == v.providerId) {
                        r.select(i);
                        t.currentOutprocessOrder.doctorName = n[i].name;
                        t.currentOutprocessOrder.doctorId = n[i].id;
                        t.currentOutprocessOrder.doctorPhone = n[i].mobile;
                        break
                    }
        })
    };
    t.initAppoint = function() {
        var n = {
            officeId: v.officeId,
            patientId: t.patientId,
            endTime: moment(Ares.today()).add(1, "d").format(l.dateFormat),
            isCancelled: !1,
            isPending: !1
        };
        c.searchAppointments(n).success(function(n) {
            var r, i;
            if (n.length > 0) t.historyAppts = n.reverse();
            else {
                t.historyAppts = null;
                return
            }
            for (i = 0; i < t.historyAppts.length; ++i) t.historyAppts[i].startTime = moment(t.historyAppts[i].startTime).format("YYYY年MM月DD日 HH:mm");
            if ($("#appoint").kendoDropDownList({
                    dataSource: t.historyAppts,
                    placeholder: "请选择",
                    valueTemplate: '<span class="k-state-default">#: data.startTime #<\/span>',
                    template: '<span class="k-state-default">#: data.startTime #<\/span>',
                    dataValueField: "id",
                    select: function(n) {
                        var i = this.dataItem(n.item.index());
                        t.currentOutprocessOrder.appointmentId = i.id
                    }
                }), r = $("#appoint").data("kendoDropDownList"), t.currentOutprocessOrder.appointmentId && t.currentOutprocessOrder.appointmentId != 0) {
                for (i = 0; i < t.historyAppts.length; ++i)
                    if (t.historyAppts[i].id == t.currentOutprocessOrder.appointmentId) {
                        r.select(i);
                        break
                    }
            } else r.select(0)
        })
    };
    var k = function() {
            return "/app/patient/views/outprocess/patient-outprocess-picture-upload.html"
        },
        d = function(n, i) {
            if (t.currentOutprocessOrder && !(i.files.length < 1)) {
                if (i.files[0].size > 1048576) {
                    t.showErrorNotification("为保证上传体验，上传图片尺寸不允许超过1M！");
                    return
                }
                var r = v.apiToken,
                    u = v.tokenType;
                i.url = v.apiHost + "/api/v1/outprocessorderpicture?orderId=" + t.currentOutprocessOrder.id;
                i.headers = i.headers || {};
                i.headers.Authorization = u + " " + r;
                i.submit();
                $("#pictureUploadPanel").fileupload("disable")
            }
        },
        g = function() {},
        nt = function() {},
        tt = function(n, i) {
            var r = parseInt(i.loaded / i.total * 100, 10);
            t.progressBarPercentage = r + "%"
        },
        it = function() {
            t.showNotification("图片上传成功！");
            t.progressBarPercentage = "0%";
            $("#pictureUploadPanel").fileupload("enable");
            t.refreshPictureList()
        },
        rt = function() {
            t.progressBarPercentage = "0%";
            t.showErrorNotification("图片上传失败！");
            $("#pictureUploadPanel").fileupload("enable")
        },
        ut = function() {
            s.getOutProcessPictures(t.currentOutprocessOrder.id).success(function(n) {
                t.pictureList = n
            })
        };
    t.cancelOutProcessOrder = function() {
        a.confirm("取消编辑", "确定要取消此次编辑的数据？").then(function() {
            f.switchState("patientOutProcess.historyRecords", {
                patientId: t.patientId
            })
        })
    };
    t.reloadSystemSettingItem = function() {
        t.colorCodeList = [];
        t.outProcessItemList = [];
        t.supplyers = [];
        t.statuses = [];
        h.getItemTypes("色号").success(function(n) {
            t.colorCodeList = n
        });
        h.getDentureProducts().success(function(n) {
            t.outProcessItemList = n
        });
        h.getItemTypes("技加工状态").success(function(n) {
            t.statuses = n
        })
    };
    p = function() {
        var i, f, n, r, u;
        if (t.currentOutprocessOrder.id == 0) t.currentOutprocessOrder.annex = [!1, !1, !1, !1, !1, !1], t.currentOutprocessOrder.doctorNotes = "", t.currentOutprocessOrder.manufactureNotes = "", t.currentOutprocessOrder.annexString = "";
        else if (t.currentOutprocessOrder.orderContent != "" && (i = angular.fromJson(t.currentOutprocessOrder.orderContent), i && angular.isArray(i)))
            for (f = 0; f < i.length; ++f)
                if (n = i[f], n.sectionName == "附录") {
                    for (t.currentOutprocessOrder.annex = n.sectionValue.split(","), r = 0; r < t.currentOutprocessOrder.annex.length; r++) t.currentOutprocessOrder.annex[r] = t.currentOutprocessOrder.annex[r] == "false" ? !1 : !0;
                    for (t.currentOutprocessOrder.annexString = "", u = 0; u < t.currentOutprocessOrder.annex.length; ++u) t.currentOutprocessOrder.annex[u] == !0 && (t.currentOutprocessOrder.annexString = t.currentOutprocessOrder.annexString + t.annexContent[u] + ",")
                } else n.sectionName == "医生备注" ? t.currentOutprocessOrder.doctorNotes = n.sectionValue : n.sectionName == "技加工生产提示" && (t.currentOutprocessOrder.manufactureNotes = n.sectionValue)
    };
    w = function() {
        var n, i;
        if (t.currentOutprocessOrder.orderType == "固定义齿") {
            for (n = [], n.push({
                    sectionName: "附录",
                    sectionValue: t.currentOutprocessOrder.annex.toString()
                }), t.currentOutprocessOrder.annexString = "", i = 0; i < t.currentOutprocessOrder.annex.length; ++i) t.currentOutprocessOrder.annex[i] == !0 && (t.currentOutprocessOrder.annexString = t.currentOutprocessOrder.annexString + t.annexContent[i] + ",");
            n.push({
                sectionName: "医生备注",
                sectionValue: t.currentOutprocessOrder.doctorNotes
            });
            n.push({
                sectionName: "技加工生产提示",
                sectionValue: t.currentOutprocessOrder.manufactureNotes
            });
            t.currentOutprocessOrder.orderContent = angular.toJson(n)
        }
    };
    t.saveOutprocessOrder = function(n) {
        var u = $("#doctor").data("kendoDropDownList"),
            r, i, f, e;
        if ((t.currentOutprocessOrder.doctorName = u.text(), t.currentOutprocessOrder.doctorId = u.value(), r = $("#appoint").data("kendoDropDownList"), !r) || (t.currentOutprocessOrder.appointmentId = r.value(), !t.currentOutprocessOrder.appointmentId)) return t.showErrorNotification("没有关联的就诊时间，请先创建预约，再保存订单！"), !1;
        if (t.currentOutprocessOrder.orderDetailList.length == 0) return t.showErrorNotification("请先添加一个产品！"), !1;
        for (i = 0; i < t.currentOutprocessOrder.orderDetailList.length; ++i) {
            if (t.currentOutprocessOrder.orderDetailList[i].fdiToothCodesArray.length == 0) return t.showErrorNotification("加工产品必须选择对应牙位！"), !1;
            t.currentOutprocessOrder.orderDetailList[i].fDIToothCodes = t.currentOutprocessOrder.orderDetailList[i].fdiToothCodesArray.join(",")
        }
        t.currentOutprocessOrder.sendDate = moment(t.currentOutprocessOrder.sendDate).format("YYYY-MM-DD HH:mm");
        t.currentOutprocessOrder.backDate = moment(t.currentOutprocessOrder.backDate).format("YYYY-MM-DD HH:mm");
        t.currentOutprocessOrder.tryDateTime && (t.currentOutprocessOrder.tryDateTime = moment(t.currentOutprocessOrder.tryDateTime).format("YYYY-MM-DD HH:mm"));
        f = $("#supplyers").data("kendoDropDownList");
        t.currentOutprocessOrder.supplyName = f.text();
        e = $("#orderStatus").data("kendoDropDownList");
        t.currentOutprocessOrder.status = e.text();
        t.saveOrderDetail();
        t.currentOutprocessOrder.id == 0 ? s.createOutProcessOrder(t.currentOutprocessOrder).success(function(i) {
            return t.currentOutprocessOrder.id = i.id, n && t.showNotification("保存成功！"), y("patientOutProcess.historyRecords"), !0
        }).error(function() {
            return t.showErrorNotification("保存失败"), !1
        }) : s.updateOutProcessOrder(t.currentOutprocessOrder).success(function() {
            n && t.showNotification("保存成功！");
            y("patientOutProcess.historyRecords")
        }).error(function() {
            return t.showErrorNotification("保存失败"), !1
        })
    };
    y = function(n) {
        f.switchState(n, b)
    };
    b = function() {
            var n = t.patientId;
            return {
                patientId: n
            }
        },
        function() {
            var i, n;
            for (t.patientId = u.params.patientId, t.appointId = u.params.apptId, t.currentOrderId = u.params.orderId, t.catagory = u.params.cata, t.buildPictureTemplateUrl = k, t.uploadStart = g, t.uploadStop = nt, t.uploadProgressed = tt, t.uploadFinished = it, t.uploadFailed = rt, t.addUpload = d, t.refreshPictureList = ut, t.saveOrderDetail = w, t.initOrderDetail = p, h.getOutProcessFactory().success(function(n) {
                    t.factoryList = new kendo.data.ObservableArray(n)
                }), i = o.officeDic.data(), n = 0; n < i.length; ++n)
                if (i[n].id == v.officeId) {
                    t.office = i[n];
                    break
                }
            o.systemsettingDic.load().then(function(n) {
                t.colorCodeList = [];
                t.supplyers = [];
                t.statuses = [];
                t.pickers = [];
                for (var i = 0; i < n.length; ++i) n[i].itemType == "色号" ? t.colorCodeList.push(n[i]) : n[i].itemType == "技加工单位" ? t.supplyers.push(n[i]) : n[i].itemType == "技加工状态" ? t.statuses.push(n[i]) : n[i].itemType == "取件人" && t.pickers.push(n[i]);
                t.currentOrderId || (t.currentOrderId = 0);
                t.editstatus = u.params.status;
                s.getPatient(t.patientId).success(function(n) {
                    t.patient = n;
                    t.currentOrderId > 0 ? s.getOutProcessOrder(t.currentOrderId).success(function(n) {
                        var r, i;
                        for (t.currentOutprocessOrder = n, t.refreshPictureList(), t.currentOutprocessOrder.viewStatus = t.editstatus && t.editstatus == 0 ? "browser" : "edit", r = 0; r < t.currentOutprocessOrder.orderDetailList.length; ++r) i = t.currentOutprocessOrder.orderDetailList[r], i.fdiToothCodes != null && i.fdiToothCodes.length > 0 && (i.fdiToothCodesArray = i.fdiToothCodes.split(","));
                        t.initOrderDetail();
                        t.currentOutprocessOrder.sendDate = moment(t.currentOutprocessOrder.sendDate).toDate();
                        t.currentOutprocessOrder.backDate = moment(t.currentOutprocessOrder.backDate).toDate();
                        t.initDoctor();
                        t.initAppoint();
                        h.getDentureProducts().success(function(n) {
                            for (var r = [], i = 0; i < n.length; ++i) n[i].productCatagory == t.currentOutprocessOrder.orderType && r.push(n[i]);
                            t.outProcessItemList = r
                        })
                    }) : t.currentOrderId == 0 && (t.createOutprocessOrder(), t.currentOutprocessOrder.viewStatus = "edit", t.initDoctor(), t.initAppoint(), h.getDentureProducts().success(function(n) {
                        for (var r = [], i = 0; i < n.length; ++i) n[i].productCatagory == t.currentOutprocessOrder.orderType && r.push(n[i]);
                        t.outProcessItemList = r
                    }))
                })
            })
        }()
}]);
patientModule.controller("PatientOutprocessCatagoryDialogCtrl", ["$log", "$scope", "$state", "$modalInstance", "appNav", function(n, t, i, r) {
    "use strict";
    var u = function() {
            r.dismiss("cancel")
        },
        f = function(n) {
            r.close(n)
        };
    (function() {
        t.cancel = u;
        t.clickCatagoryButton = f
    })()
}]);
patientModule.controller("PatientOutprocessConnectCtrl", ["$log", "$scope", "$location", "$http", "$state", "appNav", "enums", "dataDicSvc", "patientSvc", "practiceSvc", "appointmentSvc", "constants", "aresDialog", "loginContext", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v) {
    "use strict";
    var y, p;
    t.colorCodeList = {};
    t.outProcessItemList = {};
    t.supplyers = {};
    t.statuses = {};
    t.pickers = {};
    t.createOutprocessOrder = function() {
        t.currentOutprocessOrder = {
            id: 0,
            appointmentId: 0,
            pId: t.patientId,
            status: "待处理",
            supplyName: "",
            pickerName: "",
            pickerPhone: "",
            processDays: 0,
            doctorName: "",
            doctorId: 0,
            customerPrice: 0,
            factoryPrice: 0,
            notes: "",
            orderNo: "",
            sendDate: moment(new Date).format("YYYY-MM-DD HH:mm:ss"),
            backDate: moment(new Date).format("YYYY-MM-DD HH:mm:ss"),
            orderDetailList: [],
            orderType: t.catagory
        };
        t.initOrderDetail()
    };
    t.deleteOrderDetail = function(n) {
        t.currentOutprocessOrder.orderDetailList.length > 0 && t.currentOutprocessOrder.orderDetailList.splice(n, 1)
    };
    t.initDoctor = function() {
        h.getDoctors().success(function(n) {
            var r, i;
            if ($("#doctor").kendoDropDownList({
                    dataSource: n,
                    placeholder: "请选择医生",
                    dataTextField: "name",
                    dataValueField: "id",
                    select: function(n) {
                        var i = this.dataItem(n.item.index());
                        t.currentOutprocessOrder.doctorName = i.name;
                        t.currentOutprocessOrder.doctorId = i.id
                    }
                }), r = $("#doctor").data("kendoDropDownList"), t.currentOutprocessOrder && t.currentOutprocessOrder.doctorId) {
                for (i = 0; i < n.length; ++i)
                    if (n[i].id == t.currentOutprocessOrder.doctorId) {
                        r.select(i);
                        break
                    }
            } else
                for (i = 0; i < n.length; ++i)
                    if (n[i].id == v.providerId) {
                        r.select(i);
                        break
                    }
        })
    };
    t.initAppoint = function() {
        var n = {
            officeId: v.officeId,
            patientId: t.patientId,
            endTime: moment(Ares.today()).add(1, "d").format(l.dateFormat),
            isCancelled: !1,
            isPending: !1
        };
        c.searchAppointments(n).success(function(n) {
            var r, i;
            if (n.length > 0) t.historyAppts = n.reverse();
            else {
                t.historyAppts = null;
                return
            }
            for (i = 0; i < t.historyAppts.length; ++i) t.historyAppts[i].startTime = moment(t.historyAppts[i].startTime).format("YYYY年MM月DD日 HH:mm");
            if ($("#appoint").kendoDropDownList({
                    dataSource: t.historyAppts,
                    placeholder: "请选择",
                    valueTemplate: '<span class="k-state-default">#: data.startTime #<\/span>',
                    template: '<span class="k-state-default">#: data.startTime #<\/span>',
                    dataValueField: "id",
                    select: function(n) {
                        var i = this.dataItem(n.item.index());
                        t.currentOutprocessOrder.appointmentId = i.id
                    }
                }), r = $("#appoint").data("kendoDropDownList"), t.currentOutprocessOrder.appointmentId && t.currentOutprocessOrder.appointmentId != 0) {
                for (i = 0; i < t.historyAppts.length; ++i)
                    if (t.historyAppts[i].id == t.currentOutprocessOrder.appointmentId) {
                        r.select(i);
                        break
                    }
            } else r.select(0)
        })
    };
    var w = function() {
            return "/app/patient/views/outprocess/patient-outprocess-picture-upload.html"
        },
        b = function(n, i) {
            if (t.currentOutprocessOrder && !(i.files.length < 1)) {
                if (i.files[0].size > 1048576) {
                    t.showErrorNotification("为保证上传体验，上传图片尺寸不允许超过1M！");
                    return
                }
                var r = v.apiToken,
                    u = v.tokenType;
                i.url = v.apiHost + "/api/v1/outprocessorderpicture?orderId=" + t.currentOutprocessOrder.id;
                i.headers = i.headers || {};
                i.headers.Authorization = u + " " + r;
                i.submit();
                $("#pictureUploadPanel").fileupload("disable")
            }
        },
        k = function() {},
        d = function() {},
        g = function(n, i) {
            var r = parseInt(i.loaded / i.total * 100, 10);
            t.progressBarPercentage = r + "%"
        },
        nt = function() {
            t.showNotification("图片上传成功！");
            t.progressBarPercentage = "0%";
            $("#pictureUploadPanel").fileupload("enable");
            t.refreshPictureList()
        },
        tt = function() {
            t.progressBarPercentage = "0%";
            t.showErrorNotification("图片上传失败！");
            $("#pictureUploadPanel").fileupload("enable")
        },
        it = function() {
            s.getOutProcessPictures(t.currentOutprocessOrder.id).success(function(n) {
                t.pictureList = n
            })
        };
    t.cancelOutProcessOrder = function() {
        a.confirm("取消编辑", "确定要取消此次编辑的数据？").then(function() {
            f.switchState("patientOutProcess.historyRecords", {
                patientId: t.patientId
            })
        })
    };
    t.reloadSystemSettingItem = function() {
        t.colorCodeList = [];
        t.outProcessItemList = [];
        t.supplyers = [];
        t.statuses = [];
        h.getItemTypes("色号").success(function(n) {
            t.colorCodeList = n
        });
        h.getDentureProducts().success(function(n) {
            t.outProcessItemList = n
        });
        h.getItemTypes("技加工状态").success(function(n) {
            t.statuses = n
        })
    };
    var rt = function() {
            t.currentOutprocessOrder.orderType == "固定义齿" ? (t.currentOutprocessOrder.colorDetailList = [], t.currentOutprocessOrder.bridge = "", t.currentOutprocessOrder.faceType = "", t.currentOutprocessOrder.adjoin = "", t.currentOutprocessOrder.occlusion = "", t.currentOutprocessOrder.maxillofacial = "", t.currentOutprocessOrder.neckExtension = "", t.currentOutprocessOrder.clearance = "", t.currentOutprocessOrder.siliconeImpression = !1, t.currentOutprocessOrder.occlusal = !1, t.currentOutprocessOrder.involution = !1, t.currentOutprocessOrder.waxPattern = !1, t.currentOutprocessOrder.tray = !1, t.currentOutprocessOrder.pattern = !1) : t.currentOutprocessOrder.orderType == "活动义齿" && (t.currentOutprocessOrder.designList = [], t.currentOutprocessOrder.jawFrame = !1, t.currentOutprocessOrder.occlusal = !1, t.currentOutprocessOrder.involution = !1, t.currentOutprocessOrder.tray = !1, t.currentOutprocessOrder.pattern = !1)
        },
        ut = function() {
            var n, i;
            if (t.currentOutprocessOrder.orderType == "固定义齿") {
                for (n = "", i = 0; i < t.currentOutprocessOrder.colorDetailList.length; ++i) n = n + "牙位#" + t.currentOutprocessOrder.colorDetailList[i].fdiToothCodesArray.join(",") + "@", n = n + "颈#" + t.currentOutprocessOrder.colorDetailList[i].colorCode1 + "@", n = n + "中#" + t.currentOutprocessOrder.colorDetailList[i].colorCode2 + "@", n = n + "切#" + t.currentOutprocessOrder.colorDetailList[i].colorCode3 + "@", n = n + "切端透明层#" + t.currentOutprocessOrder.colorDetailList[i].clearLayer + "@", n = n + "釉质横纹#" + t.currentOutprocessOrder.colorDetailList[i].enamel + "@", n = n + "窝沟点染#" + t.currentOutprocessOrder.colorDetailList[i].fissure + "$";
                n = n + "桥体#" + t.currentOutprocessOrder.bridge + "@";
                n = n + "脸型#" + t.currentOutprocessOrder.faceType + "@";
                n = n + "邻接#" + t.currentOutprocessOrder.adjoin + "@";
                n = n + "咬合#" + t.currentOutprocessOrder.occlusion + "@";
                n = n + "金属颌面#" + t.currentOutprocessOrder.maxillofacial + "@";
                n = n + "颈缘延伸#" + t.currentOutprocessOrder.neckExtension + "@";
                n = n + "间隙#" + t.currentOutprocessOrder.clearance + "@";
                n = n + "硅胶印模#" + t.currentOutprocessOrder.siliconeImpression + "@";
                n = n + "咬合记录#" + t.currentOutprocessOrder.occlusal + "@";
                n = n + "无对合#" + t.currentOutprocessOrder.involution + "@";
                n = n + "诊断蜡型#" + t.currentOutprocessOrder.waxPattern + "@";
                n = n + "参考模型#" + t.currentOutprocessOrder.pattern + "@";
                n = n + "托盘#" + t.currentOutprocessOrder.tray + "@";
                t.currentOutprocessOrder.orderContent = n
            } else if (t.currentOutprocessOrder.orderType == "活动义齿") {
                for (n = "", i = 0; i < t.currentOutprocessOrder.designList.length; ++i) n = n + "牙位#" + t.currentOutprocessOrder.designList[i].fdiToothCodesArray.join(",") + "@", n = n + "合支托#" + t.currentOutprocessOrder.designList[i].occlusalRest + "@", n = n + "邻面板#" + t.currentOutprocessOrder.designList[i].adjacentPanel + "@", n = n + "卡环#" + t.currentOutprocessOrder.designList[i].snapRing + "@", n = n + "附着体#" + t.currentOutprocessOrder.designList[i].attachment + "$";
                n = n + "咬合记录#" + t.currentOutprocessOrder.occlusal + "@";
                n = n + "无对合#" + t.currentOutprocessOrder.involution + "@";
                n = n + "颌架#" + t.currentOutprocessOrder.jawFrame + "@";
                n = n + "参考模型#" + t.currentOutprocessOrder.pattern + "@";
                n = n + "托盘#" + t.currentOutprocessOrder.tray + "@";
                t.currentOutprocessOrder.orderContent = n
            }
        },
        ft = function() {
            var r, u, e, o, f, s, i, n;
            if (t.currentOutprocessOrder.orderType == "固定义齿") {
                if (t.currentOutprocessOrder.colorDetailList = [], !t.currentOutprocessOrder.orderContent) return;
                if (u = t.currentOutprocessOrder.orderContent.split("$"), u.length > 1) {
                    for (e = 0; e < u.length - 1; ++e) {
                        for (o = u[e].split("@"), r = {}, i = 0; i < o.length; ++i) n = o[i], n.indexOf("牙位") >= 0 ? (r.fdiToothCodes = n.substr(3), r.fdiToothCodes != null && r.fdiToothCodes.length > 0 && (r.fdiToothCodesArray = r.fdiToothCodes.split(","))) : n.indexOf("颈#") >= 0 ? r.colorCode1 = n.substr(2) : n.indexOf("中#") >= 0 ? r.colorCode2 = n.substr(2) : n.indexOf("切#") >= 0 ? r.colorCode3 = n.substr(2) : n.indexOf("切端透明层") >= 0 ? r.clearLayer = n.substr(6) == "true" ? !0 : !1 : n.indexOf("釉质横纹") >= 0 ? r.enamel = n.substr(5) == "true" ? !0 : !1 : n.indexOf("窝沟点染") >= 0 && (r.fissure = n.substr(5) == "true" ? !0 : !1);
                        t.currentOutprocessOrder.colorDetailList.push(r)
                    }
                    for (s = u[u.length - 1].split("@"), i = 0; i < s.length; ++i) n = s[i], n.indexOf("桥体") >= 0 ? t.currentOutprocessOrder.bridge = n.substr(3) : n.indexOf("脸型") >= 0 ? t.currentOutprocessOrder.faceType = n.substr(3) : n.indexOf("邻接") >= 0 ? t.currentOutprocessOrder.adjoin = n.substr(3) : n.indexOf("咬合@") >= 0 ? t.currentOutprocessOrder.occlusion = n.substr(3) : n.indexOf("金属颌面") >= 0 ? t.currentOutprocessOrder.maxillofacial = n.substr(5) : n.indexOf("颈缘延伸") >= 0 ? t.currentOutprocessOrder.neckExtension = n.substr(5) : n.indexOf("间隙") >= 0 ? t.currentOutprocessOrder.clearance = n.substr(3) : n.indexOf("硅胶印模") >= 0 ? t.currentOutprocessOrder.siliconeImpression = n.substr(5) == "true" ? !0 : !1 : n.indexOf("咬合记录") >= 0 ? t.currentOutprocessOrder.occlusal = n.substr(5) == "true" ? !0 : !1 : n.indexOf("无对合") >= 0 ? t.currentOutprocessOrder.involution = n.substr(4) == "true" ? !0 : !1 : n.indexOf("诊断蜡型") >= 0 ? t.currentOutprocessOrder.waxPattern = n.substr(5) == "true" ? !0 : !1 : n.indexOf("参考模型") >= 0 ? t.currentOutprocessOrder.pattern = n.substr(5) == "true" ? !0 : !1 : n.indexOf("托盘") >= 0 && (t.currentOutprocessOrder.tray = n.substr(3) == "true" ? !0 : !1)
                }
            } else if (t.currentOutprocessOrder.orderType == "活动义齿") {
                if (t.currentOutprocessOrder.designList = [], !t.currentOutprocessOrder.orderContent) return;
                if (u = t.currentOutprocessOrder.orderContent.split("$"), u.length > 1) {
                    for (e = 0; e < u.length - 1; ++e) {
                        for (o = u[e].split("@"), f = {}, i = 0; i < o.length; ++i) n = o[i], n.indexOf("牙位") >= 0 ? (f.fdiToothCodes = n.substr(3), f.fdiToothCodes != null && f.fdiToothCodes.length > 0 && (f.fdiToothCodesArray = f.fdiToothCodes.split(","))) : n.indexOf("合支托") >= 0 ? f.occlusalRest = n.substr(4) : n.indexOf("邻面板") >= 0 ? f.adjacentPanel = n.substr(4) : n.indexOf("卡环") >= 0 ? f.snapRing = n.substr(3) : n.indexOf("附着体") >= 0 && (f.attachment = n.substr(4) == "true" ? !0 : !1);
                        t.currentOutprocessOrder.designList.push(f)
                    }
                    for (s = u[u.length - 1].split("@"), i = 0; i < s.length; ++i) n = s[i], n.indexOf("咬合记录") >= 0 ? t.currentOutprocessOrder.occlusal = n.substr(5) == "true" ? !0 : !1 : n.indexOf("无对合") >= 0 ? t.currentOutprocessOrder.involution = n.substr(4) == "true" ? !0 : !1 : n.indexOf("颌架") >= 0 ? t.currentOutprocessOrder.jawFrame = n.substr(3) == "true" ? !0 : !1 : n.indexOf("参考模型") >= 0 ? t.currentOutprocessOrder.pattern = n.substr(5) == "true" ? !0 : !1 : n.indexOf("托盘") >= 0 && (t.currentOutprocessOrder.tray = n.substr(3) == "true" ? !0 : !1)
                }
            }
        };
    t.saveOutprocessOrder = function() {
        var r = $("#doctor").data("kendoDropDownList"),
            i, n, u, f;
        if (t.currentOutprocessOrder.doctorName = r.text(), t.currentOutprocessOrder.doctorId = r.value(), i = $("#appoint").data("kendoDropDownList"), !i) {
            t.showErrorNotification("没有关联的就诊时间，请先创建预约，再保存订单！");
            return
        }
        if (t.currentOutprocessOrder.appointmentId = i.value(), !t.currentOutprocessOrder.appointmentId) {
            t.showErrorNotification("没有关联的就诊时间，请先创建预约，再保存订单！");
            return
        }
        for (n = 0; n < t.currentOutprocessOrder.orderDetailList.length; ++n) t.currentOutprocessOrder.orderDetailList[n].fDIToothCodes = t.currentOutprocessOrder.orderDetailList[n].fdiToothCodesArray.join(",");
        t.currentOutprocessOrder.sendDate = moment(t.currentOutprocessOrder.sendDate).format("YYYY-MM-DD HH:mm");
        t.currentOutprocessOrder.backDate = moment(t.currentOutprocessOrder.backDate).format("YYYY-MM-DD HH:mm");
        t.currentOutprocessOrder.tryDateTime && (t.currentOutprocessOrder.tryDateTime = moment(t.currentOutprocessOrder.tryDateTime).format("YYYY-MM-DD HH:mm"));
        u = $("#supplyers").data("kendoDropDownList");
        t.currentOutprocessOrder.supplyName = u.text();
        f = $("#orderStatus").data("kendoDropDownList");
        t.currentOutprocessOrder.status = f.text();
        t.saveOrderDetail();
        t.currentOutprocessOrder.id == 0 ? s.createOutProcessOrder(t.currentOutprocessOrder).success(function(n) {
            t.currentOutprocessOrder.id = n.id;
            t.showNotification("保存成功！");
            y("patientOutProcess.historyRecords")
        }).error(function() {
            t.showErrorNotification("保存失败")
        }) : s.updateOutProcessOrder(t.currentOutprocessOrder).success(function() {
            t.showNotification("保存成功！");
            y("patientOutProcess.historyRecords")
        }).error(function() {
            t.showErrorNotification("保存失败")
        })
    };
    y = function(n) {
        f.switchState(n, p)
    };
    p = function() {
            var n = t.patientId;
            return {
                patientId: n
            }
        },
        function() {
            var i, n;
            for (t.patientId = u.params.patientId, t.appointId = u.params.apptId, t.currentOrderId = u.params.orderId, t.catagory = u.params.cata, t.buildPictureTemplateUrl = w, t.uploadStart = k, t.uploadStop = d, t.uploadProgressed = g, t.uploadFinished = nt, t.uploadFailed = tt, t.addUpload = b, t.refreshPictureList = it, t.saveOrderDetail = ut, t.loadOrderDetail = ft, t.initOrderDetail = rt, h.getOutProcessFactory().success(function(n) {
                    t.factoryList = new kendo.data.ObservableArray(n)
                }), i = o.officeDic.data(), n = 0; n < i.length; ++n)
                if (i[n].id == v.officeId) {
                    t.office = i[n];
                    break
                }
            o.systemsettingDic.load().then(function(n) {
                t.colorCodeList = [];
                t.supplyers = [];
                t.statuses = [];
                t.pickers = [];
                t.snapRingList = [];
                t.attachmentList = [];
                t.occlusalRestList = [];
                t.adjacentPanelList = [];
                t.implantList = [];
                for (var i = 0; i < n.length; ++i) n[i].itemType == "色号" ? t.colorCodeList.push(n[i]) : n[i].itemType == "技加工单位" ? t.supplyers.push(n[i]) : n[i].itemType == "技加工状态" ? t.statuses.push(n[i]) : n[i].itemType == "取件人" ? t.pickers.push(n[i]) : n[i].itemType == "技加工卡环类型" ? t.snapRingList.push(n[i]) : n[i].itemType == "技加工附着体类型" ? t.attachmentList.push(n[i]) : n[i].itemType == "技加工合支托类型" ? t.occlusalRestList.push(n[i]) : n[i].itemType == "技加工邻面板类型" ? t.adjacentPanelList.push(n[i]) : n[i].itemType == "技加工人工牙" && t.implantList.push(n[i]);
                t.currentOrderId || (t.currentOrderId = 0);
                t.editstatus = u.params.status;
                s.getPatient(t.patientId).success(function(n) {
                    t.patient = n;
                    t.currentOrderId > 0 ? s.getOutProcessOrder(t.currentOrderId).success(function(n) {
                        var r, i;
                        for (t.currentOutprocessOrder = n, t.refreshPictureList(), t.currentOutprocessOrder.viewStatus = t.editstatus && t.editstatus == 0 ? "browser" : "edit", r = 0; r < t.currentOutprocessOrder.orderDetailList.length; ++r) i = t.currentOutprocessOrder.orderDetailList[r], i.fdiToothCodes != null && i.fdiToothCodes.length > 0 && (i.fdiToothCodesArray = i.fdiToothCodes.split(","));
                        t.initOrderDetail();
                        t.loadOrderDetail();
                        t.currentOutprocessOrder.sendDate = moment(t.currentOutprocessOrder.sendDate).toDate();
                        t.currentOutprocessOrder.backDate = moment(t.currentOutprocessOrder.backDate).toDate();
                        t.initDoctor();
                        t.initAppoint();
                        h.getDentureProducts().success(function(n) {
                            for (var r = [], i = 0; i < n.length; ++i) n[i].productCatagory == t.currentOutprocessOrder.orderType && r.push(n[i]);
                            t.outProcessItemList = r
                        })
                    }) : t.currentOrderId == 0 && (t.createOutprocessOrder(), t.currentOutprocessOrder.viewStatus = "edit", t.initDoctor(), t.initAppoint(), h.getDentureProducts().success(function(n) {
                        for (var r = [], i = 0; i < n.length; ++i) n[i].productCatagory == t.currentOutprocessOrder.orderType && r.push(n[i]);
                        t.outProcessItemList = r
                    }))
                })
            })
        }()
}]);
patientModule.controller("PatientOutprocessEditCtrl", ["$log", "$scope", "$timeout", "$location", "permissionProvider", "$state", "appNav", "enums", "dataDicSvc", "patientSvc", "practiceSvc", "appointmentSvc", "constants", "aresDialog", "loginContext", "aresNotification", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p) {
    "use strict";
    var w, d;
    t.colorCodeList = {};
    t.outProcessItemList = {};
    t.supplyers = {};
    t.statuses = {};
    t.pickers = {};
    t.createOutprocessOrder = function() {
        t.currentOutprocessOrder = {
            id: 0,
            appointmentId: 0,
            pId: t.patientId,
            status: "待处理",
            supplyName: "",
            pickerName: "",
            pickerPhone: "",
            processDays: 0,
            doctorName: "",
            doctorId: 0,
            customerPrice: 0,
            factoryPrice: 0,
            notes: "",
            orderNo: "",
            sendDate: moment(new Date).format("YYYY-MM-DD HH:mm:ss"),
            backDate: moment(new Date).format("YYYY-MM-DD HH:mm:ss"),
            orderDetailList: []
        };
        t.addOrderDetail()
    };
    t.deleteOrderDetail = function(n) {
        t.currentOutprocessOrder.orderDetailList.splice(n, 1);
        t.currentOutprocessOrder.orderDetailList.length == 0 && (t.currentOutprocessOrder.orderDetailList.push({
            id: 0,
            fDIToothCodes: "",
            fdiToothCodesArray: [],
            colorCode: "",
            itemName: ""
        }), i(function() {
            t.currentOutprocessOrder.orderDetailList && angular.forEach(t.currentOutprocessOrder.orderDetailList, function(n, i) {
                i == 0 && (t.initProcessItemDropDown(i, n.itemName), t.initColorCodeDropDown(i, n.colorCode))
            })
        }, 200))
    };
    t.addOrderDetail = function() {
        t.currentOutprocessOrder.orderDetailList.push({
            id: 0,
            fDIToothCodes: "",
            fdiToothCodesArray: [],
            colorCode: "",
            itemName: "",
            count: ""
        });
        i(function() {
            t.currentOutprocessOrder.orderDetailList && angular.forEach(t.currentOutprocessOrder.orderDetailList, function(n, i) {
                i == t.currentOutprocessOrder.orderDetailList.length - 1 && i > 0 && (t.initProcessItemDropDown(i, n.itemName), t.initColorCodeDropDown(i, n.colorCode))
            })
        }, 200)
    };
    t.refreshDrop = function() {
        i(function() {
            t.currentOutprocessOrder && t.currentOutprocessOrder.orderDetailList && angular.forEach(t.currentOutprocessOrder.orderDetailList, function(n, i) {
                t.initProcessItemDropDown(i, n.itemName);
                t.initColorCodeDropDown(i, n.colorCode)
            })
        }, 200)
    };
    t.initDoctor = function() {
        c.getDoctors().success(function(n) {
            var r, u, f, i;
            if ($("#doctor").kendoDropDownList({
                    dataSource: n,
                    placeholder: "请选择医生",
                    dataTextField: "name",
                    dataValueField: "id",
                    select: function(n) {
                        var i = this.dataItem(n.item.index());
                        t.currentOutprocessOrder.doctorName = i.name;
                        t.currentOutprocessOrder.doctorId = i.id
                    }
                }), r = $("#doctor").data("kendoDropDownList"), t.currentOutprocessOrder && t.currentOutprocessOrder.doctorId) {
                for (u = t.currentOutprocessOrder.doctorId, f = _.find(n, function(n) {
                        return n.id === u
                    }), f || (n.push({
                        id: u,
                        name: t.currentOutprocessOrder.doctorName
                    }), r.setDataSource(n)), i = 0; i < n.length; ++i)
                    if (n[i].id == u) {
                        r.select(i);
                        break
                    }
            } else
                for (i = 0; i < n.length; ++i)
                    if (n[i].id == y.providerId) {
                        r.select(i);
                        break
                    }
        })
    };
    t.initSuppliers = function() {
        var i, n;
        if ($("#supplyers").kendoDropDownList({
                dataSource: t.supplyers,
                placeholder: "请选择加工厂商",
                dataTextField: "itemName",
                dataValueField: "id",
                select: function(n) {
                    var i = this.dataItem(n.item.index());
                    t.currentOutprocessOrder.supplyName = i.name
                }
            }), i = $("#supplyers").data("kendoDropDownList"), t.currentOutprocessOrder && t.currentOutprocessOrder.supplyName) {
            for (n = 0; n < t.supplyers.length; ++n)
                if (t.supplyers[n].itemName == t.currentOutprocessOrder.supplyName) {
                    i.select(n);
                    break
                }
        } else i.select(0)
    };
    t.initPickers = function() {
        var i, n;
        if ($("#picker").kendoDropDownList({
                dataSource: t.pickers,
                placeholder: "请选择取件人",
                dataTextField: "itemName",
                dataValueField: "id",
                select: function(n) {
                    var i = this.dataItem(n.item.index());
                    t.currentOutprocessOrder.pickerName = i.name
                }
            }), i = $("#picker").data("kendoDropDownList"), t.currentOutprocessOrder && t.currentOutprocessOrder.pickerName) {
            for (n = 0; n < t.pickers.length; ++n)
                if (t.pickers[n].itemName == t.currentOutprocessOrder.pickerName) {
                    i.select(n);
                    break
                }
        } else i && i.select(0)
    };
    t.initStatus = function() {
        var i, n;
        if ($("#orderStatus").kendoDropDownList({
                dataSource: t.statuses,
                placeholder: "请选择订单状态",
                dataTextField: "itemName",
                dataValueField: "id",
                select: function(n) {
                    var i = this.dataItem(n.item.index());
                    t.currentOutprocessOrder.status = i.name
                }
            }), i = $("#orderStatus").data("kendoDropDownList"), t.currentOutprocessOrder && t.currentOutprocessOrder.status) {
            for (n = 0; n < t.statuses.length; ++n)
                if (t.statuses[n].itemName == t.currentOutprocessOrder.status) {
                    i.select(n);
                    break
                }
        } else i.select(0)
    };
    t.initAppoint = function() {
        var n = {
            officeId: y.officeId,
            patientId: t.patientId,
            endTime: moment(Ares.today()).add(1, "d").format(a.dateFormat),
            isCancelled: !1,
            isPending: !1
        };
        l.searchAppointments(n).success(function(n) {
            var r, i;
            if (n.length > 0) t.historyAppts = n.reverse();
            else {
                t.historyAppts = null;
                return
            }
            for (i = 0; i < t.historyAppts.length; ++i) t.historyAppts[i].startTime = moment(t.historyAppts[i].startTime).format("YYYY年MM月DD日 HH:mm");
            if ($("#appoint").kendoDropDownList({
                    dataSource: t.historyAppts,
                    placeholder: "请选择",
                    valueTemplate: '<span class="k-state-default">#: data.startTime #<\/span>',
                    template: '<span class="k-state-default">#: data.startTime #<\/span>',
                    dataValueField: "id",
                    select: function(n) {
                        var i = this.dataItem(n.item.index());
                        t.currentOutprocessOrder.appointmentId = i.id
                    }
                }), r = $("#appoint").data("kendoDropDownList"), t.currentOutprocessOrder.appointmentId && t.currentOutprocessOrder.appointmentId != 0) {
                for (i = 0; i < t.historyAppts.length; ++i)
                    if (t.historyAppts[i].id == t.currentOutprocessOrder.appointmentId) {
                        r.select(i);
                        break
                    }
            } else r.select(0)
        })
    };
    t.cancelOutProcessOrder = function() {
        v.confirm("取消编辑", "确定要取消此次编辑的数据？").then(function() {
            e.switchState("patientOutProcess.historyRecords", {
                patientId: t.patientId
            })
        })
    };
    t.reloadSystemSettingItem = function() {
        t.colorCodeList = [];
        t.outProcessItemList = [];
        t.supplyers = [];
        t.statuses = [];
        c.getItemTypes("色号").success(function(n) {
            t.colorCodeList = n;
            c.getItemTypes("技加工项目").success(function(n) {
                t.outProcessItemList = n;
                t.isLoadOK = !0
            })
        });
        c.getItemTypes("技加工状态").success(function(n) {
            t.statuses = n
        })
    };
    var g = function(n, t) {
            c.createSystemSettingItem(n).success(function() {
                b(n, t)
            }).error(function(i) {
                i.name == "SystemSettingItemNameNotUniqueException" && (v.warn("警告", "已经有其他项目使用此名称，请更换新名称！"), b(n, t))
            })
        },
        b = function(n, t) {
            c.getItemTypes(n.itemType).success(function(n) {
                for (var i = 0; i < n.length; i++)(n[i].displayOrder == null || n[i].displayOrder != i) && (n[i].displayOrder = i);
                t = n
            })
        },
        k = function(n, i) {
            angular.forEach(t.getDropDownValue(n), function(n) {
                var t = !0,
                    u, r;
                angular.forEach(i, function(i) {
                    i.itemName == n && t && (t = !1)
                });
                t && (u = i && i.length > 0 ? i[0].itemType : "技加工项目", r = {
                    itemName: n,
                    itemType: u
                }, i.push(r), g(r))
            })
        };
    t.saveOutprocessOrder = function() {
        var f = $("#doctor").data("kendoDropDownList"),
            i, n, r, u, e, o, s;
        if (t.currentOutprocessOrder.doctorName = f.text(), t.currentOutprocessOrder.doctorId = f.value(), i = $("#appoint").data("kendoDropDownList"), !i) {
            v.warn("信息", "没有关联的就诊时间，请先创建预约，再保存订单！");
            return
        }
        if (t.currentOutprocessOrder.appointmentId = i.value(), !t.currentOutprocessOrder.appointmentId) {
            v.warn("信息", "没有关联的就诊时间，请先创建预约，再保存订单！");
            return
        }
        for (n = 0; n < t.currentOutprocessOrder.orderDetailList.length; ++n) t.currentOutprocessOrder.orderDetailList[n].fdiToothCodesArray && (t.currentOutprocessOrder.orderDetailList[n].fDIToothCodes = t.currentOutprocessOrder.orderDetailList[n].fdiToothCodesArray.join(","), r = t.getDropDownValue("#processItem" + n), r && (t.currentOutprocessOrder.orderDetailList[n].itemName = r.join(",")), k("#processItem" + n, t.outProcessItemList), u = t.getDropDownValue("#colorCode" + n), u && (t.currentOutprocessOrder.orderDetailList[n].colorCode = u.join(",")), k("#colorCode" + n, t.colorCodeList));
        t.currentOutprocessOrder.sendDate = moment(t.currentOutprocessOrder.sendDate).format("YYYY-MM-DD HH:mm");
        t.currentOutprocessOrder.backDate = moment(t.currentOutprocessOrder.backDate).format("YYYY-MM-DD HH:mm");
        e = $("#supplyers").data("kendoDropDownList");
        t.currentOutprocessOrder.supplyName = e.text();
        o = $("#picker").data("kendoDropDownList");
        t.currentOutprocessOrder.pickerName = o.text();
        s = $("#orderStatus").data("kendoDropDownList");
        t.currentOutprocessOrder.status = s.text();
        t.currentOutprocessOrder.id == 0 ? h.createOutProcessOrder(t.currentOutprocessOrder).success(function(n) {
            t.currentOutprocessOrder.id = n.id;
            p.success("技加工记录保存成功!");
            w("patientOutProcess.historyRecords")
        }).error(function() {
            v.warn("信息", "技加工记录保存失败")
        }) : h.updateOutProcessOrder(t.currentOutprocessOrder).success(function() {
            p.success("技加工记录保存成功!");
            w("patientOutProcess.historyRecords")
        }).error(function() {
            v.warn("信息", "技加工记录保存失败")
        })
    };
    w = function(n) {
        e.switchState(n, d)
    };
    d = function() {
        var n = t.patientId;
        return {
            patientId: n
        }
    };
    t.allowed = u.isAllowed("patientOutProcess.viewPrice");
    s.systemsettingDic.load().then(function(n) {
        t.colorCodeList = [];
        t.outProcessItemList = [];
        t.supplyers = [];
        t.statuses = [];
        t.pickers = [];
        for (var i = 0; i < n.length; ++i) n[i].itemType == "色号" ? t.colorCodeList.push(n[i]) : n[i].itemType == "技加工项目" ? t.outProcessItemList.push(n[i]) : n[i].itemType == "技加工单位" ? t.supplyers.push(n[i]) : n[i].itemType == "技加工状态" ? t.statuses.push(n[i]) : n[i].itemType == "取件人" && t.pickers.push(n[i]);
        t.patientId = f.params.patientId;
        t.appointId = f.params.apptId;
        t.currentOrderId = f.params.orderId;
        t.currentOrderId || (t.currentOrderId = 0);
        t.editstatus = f.params.status;
        h.getPatient(t.patientId).success(function(n) {
            t.patient = n;
            t.currentOrderId > 0 ? h.getOutProcessOrder(t.currentOrderId).success(function(n) {
                var r, i;
                for (t.currentOutprocessOrder = n, t.currentOutprocessOrder.viewStatus = t.editstatus && t.editstatus == 0 ? "browser" : "edit", r = 0; r < t.currentOutprocessOrder.orderDetailList.length; ++r) i = t.currentOutprocessOrder.orderDetailList[r], i.fdiToothCodes != null && i.fdiToothCodes.length > 0 && (i.fdiToothCodesArray = i.fdiToothCodes.split(","));
                t.currentOutprocessOrder.sendDate = moment(t.currentOutprocessOrder.sendDate).toDate();
                t.currentOutprocessOrder.backDate = moment(t.currentOutprocessOrder.backDate).toDate();
                t.initDoctor();
                t.initAppoint();
                t.initSuppliers();
                t.initPickers();
                t.initStatus();
                t.reloadSystemSettingItem()
            }) : t.currentOrderId == 0 && (t.createOutprocessOrder(), t.currentOutprocessOrder.viewStatus = "edit", t.initDoctor(), t.initAppoint(), t.initSuppliers(), t.initPickers(), t.initStatus(), t.reloadSystemSettingItem())
        })
    })
}]);
patientModule.controller("PatientOutprocessStatusDialogCtrl", ["$log", "$scope", "$state", "$modalInstance", "appNav", "host", function(n, t, i, r, u, f) {
    "use strict";
    var e = function() {
        r.dismiss("cancel")
    };
    (function() {
        t.cancel = e;
        f.orderProcedureList && (t.orderProcedureList = f.orderProcedureList)
    })()
}]);
patientModule.controller("PatientOutprocessCtrl", ["$log", "$scope", "$filter", "$timeout", "$state", "appNav", "patientSvc", "practiceSvc", "aresDialog", "loginContext", "dataDicSvc", "printUtil", "patientUtil", function(n, t, i, r, u, f, e, o, s, h, c, l, a) {
    "use strict";
    var v, y, p;
    t.outProcessOrders = [];
    v = i("toOfficeAbbr");
    t.listPatientOutProcessOrders = function() {
        t.outProcessOrders = [];
        e.listOutProcessOrdersForPatient(t.patientId).success(function(n) {
            for (var i = 0; i < n.length; i++) n[i].officeName = v(n[i].officeId), n[i].sendDate = n[i].sendDate ? moment(n[i].sendDate).format("YYYY-MM-DD HH:mm") : "", n[i].backDate = n[i].backDate ? moment(n[i].backDate).format("YYYY-MM-DD HH:mm") : "", n[i].index = i + 1;
            t.outProcessOrders = n.reverse()
        }).error(function() {
            t.outProcessOrders = [];
            alert("系统工作忙")
        })
    };
    t.deleteOutProcessOrder = function(n) {
        if (n.networkOrderId != null && n.networkOrderId != "") {
            t.showErrorNotification("已发送到技加工厂的订单无法删除！");
            return
        }
        s.confirm("删除技加工订单记录", "确定要删除此技加工记录？").then(function() {
            e.deleteOutProcessOrder(n.id).success(function() {
                t.listPatientOutProcessOrders()
            }).error(function() {
                alert("系统工作忙")
            })
        })
    };
    y = function(n) {
        var i = angular.copy(n);
        angular.forEach(i.orderDetailList, function(n) {
            n.fdiToothCodes != null && (n.fdiToothCodesArray = n.fdiToothCodes.split(","))
        });
        t.currentOutprocessOrder = i;
        r(function() {
            l.printElem("singleOutProcessPrintDiv")
        })
    };
    p = function(n) {
        a.showOperationLog(n.id, "OutProcessOrder")
    };
    t.editOutProcessOrder = function(n) {
            if (n.officeId != h.officeId) {
                t.showErrorNotification("不可修改其他诊所的技加工记录");
                return
            }
            var i = !1;
            o.getSystemConfigByName("AllowConnectFactory").success(function(r) {
                r.configValue == "true" && (i = !0);
                i == !1 ? f.switchState("patientOutProcess.createRecord", {
                    patientId: t.patientId,
                    orderId: n.id,
                    status: 1
                }) : n.orderType == "固定义齿" ? f.switchState("patientOutProcess.createFixedDentureRecord", {
                    patientId: t.patientId,
                    orderId: n.id,
                    status: 1,
                    cata: n.orderType
                }) : f.switchState("patientOutProcess.createConnectRecord", {
                    patientId: t.patientId,
                    orderId: n.id,
                    status: 1
                })
            })
        },
        function() {
            t.viewOutProcessOrderLog = p;
            t.printOutProcessOrder = y;
            t.patientId = u.params.patientId;
            t.appointId = u.params.apptId;
            e.getPatient(t.patientId).success(function(n) {
                t.patient = n
            });
            c.officeDic.load().then(function(n) {
                t.officeList = n
            });
            t.officeId = h.officeId;
            t.isRegularChain = t.$root.isRegularChain;
            t.listPatientOutProcessOrders()
        }();
    t.createOp = function() {}
}]);
patientModule.controller("AllPatientCtrl", ["$log", "$scope", "$modal", "appNav", "constants", "enums", "patientSvc", "formatUtil", "shortMessageUtil", "aresDialog", "patientUtil", "reportSvc", "loginContext", "aresNotification", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v) {
    "use strict";
    var w = function(n) {
            t.pageIndex = n;
            p(t.searchString, t.pageIndex)
        },
        y = function() {
            t.pageIndex = 1;
            p(t.searchString, t.pageIndex)
        },
        p = function(n, i, r) {
            t.isSearching = !0;
            b(n, i).success(function(i) {
                (t.isSearching = !1, n === t.searchString) && (o.formatPatients(i.items), t.searchResult = i, r && r(i))
            }).error(function() {
                t.isSearching = !1
            })
        },
        b = function(n, i) {
            return t.isSearchByDoctor ? e.getPatientByDoctor(a.providerId, i, t.pageSize) : e.getAll(n, i, t.pageSize)
        },
        k = function(n, t) {
            s.sendMessage(n, t)
        },
        d = function(i) {
            c.deletePatient(i).then(function(r) {
                r == "deleted" || r == "archived" ? (c.removePatientFromPatientList(i, t.searchResult.items), t.refreshPatientGrid()) : n.error("Delete patient result is unkown.")
            })
        },
        g = function(n) {
            c.createFollowUpApptByPatientId(n).then(function() {
                v.success("预约成功")
            })
        };
    (function() {
        t.searchString = "";
        t.pageIndex = 1;
        t.pageSize = 10;
        t.isSearchByDoctor = a.roleType == "牙医";
        t.maxPageCount = 10;
        t.onPageChanged = w;
        t.sendMessage = k;
        t.deletePatient = d;
        t.createFollowUpAppt = g;
        t.$watch("searchString", function() {
            t.isInitialized() && y()
        });
        t.$watch("isSearchByDoctor", function() {
            t.isInitialized() && y()
        });
        y()
    })()
}]);
patientModule.controller("ArchivedPatientListCtrl", ["$log", "$scope", "patientSvc", "formatUtil", "patientUtil", function(n, t, i, r, u) {
    "use strict";
    var o = function(n) {
            t.pageIndex = n;
            e(t.searchString, t.pageIndex)
        },
        f = function() {
            t.pageIndex = 1;
            e(t.searchString, t.pageIndex)
        },
        e = function(n, u, f) {
            t.isSearching = !0;
            i.searchArchivedPatients(n, u, t.pageSize).success(function(i) {
                (t.isSearching = !1, n === t.searchString) && (r.formatPatients(i.items), t.searchResult = i, f && f(i))
            }).error(function() {
                t.isSearching = !1
            })
        },
        s = function(n) {
            u.undoArchive(n).then(function() {
                u.removePatientFromPatientList(n, t.searchResult.items);
                t.refreshPatientGrid()
            })
        },
        h = function(i) {
            u.deletePatient(i, !0).then(function(r) {
                r == "deleted" ? (u.removePatientFromPatientList(i, t.searchResult.items), t.refreshPatientGrid()) : n.error("Delete patient result [" + r + "] is unkown.")
            })
        };
    (function() {
        t.searchString = "";
        t.pageIndex = 1;
        t.pageSize = 10;
        t.maxPageCount = 10;
        t.onPageChanged = o;
        t.undoArchive = s;
        t.deletePatient = h;
        t.$watch("searchString", function() {
            t.isInitialized() && f()
        });
        f()
    })()
}]);
patientModule.controller("DuplicatedPatientCtrl", ["$log", "$q", "$scope", "patientSvc", "formatUtil", "sessionCache", "aresDialog", "patientUtil", function(n, t, i, r, u, f, e, o) {
    "use strict";
    var h = f.getCache(f.keys.DuplicatedPatientSearchCriteria),
        s = {
            byName: !1,
            byMobile: !1,
            name: "",
            mobile: "",
            pageIndex: 1,
            pageSize: 10
        },
        c = function() {
            var n = h.loadObject();
            n && _.extend(s, n)
        },
        l = function(n, f) {
            var e = t.defer();
            return s.pageIndex = n, s.pageSize = f, h.saveObject(s), r.searchDuplicated(s).success(function(n) {
                i.isSearching = !1;
                u.formatPatients(n.items);
                i.searchResult = n;
                e.resolve({
                    total: n.totalCount,
                    data: n.items
                })
            }).error(function() {
                i.isSearching = !1;
                e.resolve(!1)
            }), e.promise
        },
        a = function(t) {
            o.deletePatient(t).then(function(r) {
                r == "deleted" || r == "archived" ? (o.removePatientFromPatientList(t, i.searchResult.items), i.refreshPatientGrid()) : n.error("Delete patient result is unkown.")
            })
        };
    (function() {
        i.criteria = s;
        i.pageIndex = 1;
        i.pageSize = 10;
        i.search = l;
        i.deletePatient = a;
        c()
    })()
}]);
patientModule.controller("SearchPatientDemoCtrl", ["$log", "$scope", "$modal", "dataDicSvc", "$q", "providerSvc", "patientSvc", "formatUtil", "shortMessageUtil", "aresDialog", "patientUtil", "reportSvc", "loginContext", "practiceSvc", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v) {
    "use strict";
    var y = function() {
            v.getSearchConfigAll().success(function(n) {
                var i, r;
                t.searchConfigs = n;
                t.copySearchCondFields = angular.copy(t.searchConfigs[0].searchCondFields);
                t.isDoctor && (i = _.find(t.searchConfigs, function(n) {
                    return n.name == "全部患者" && n.id == 0
                }), i && i.isPreferred && (i.isPreferred = !1, r = _.find(t.searchConfigs, function(n) {
                    return n.name == "我的患者"
                }), r.isPreferred = !0))
            })
        },
        p = function() {
            var n = u.defer();
            return r.sourceTypeDic.loadActive().then(function(i) {
                t.sourceTypeData = i;
                n.resolve(!0)
            }), n.promise
        },
        w = function() {
            var n = u.defer();
            return r.doctorDic.loadActive().then(function(i) {
                t.doctorData = i;
                n.resolve(!0)
            }), n.promise
        },
        b = function() {
            var n = u.defer();
            return v.getItemTypes("patientType").success(function(i) {
                t.patientTypeData = i;
                n.resolve(!0)
            }), n.promise
        },
        k = function() {
            var n = u.defer();
            return f.getOtherProvider().success(function(i) {
                t.providers = i;
                n.resolve(!0)
            }), n.promise
        },
        d = function() {
            p().then(function() {
                w().then(function() {
                    b().then(function() {
                        k().then(function() {
                            y()
                        })
                    })
                })
            })
        },
        g = function(n) {
            t.searchConfig = t.searchConfigs[0];
            t.searchConfig.searchCondFields = angular.copy(t.copySearchCondFields);
            var i = u.defer(),
                r = {
                    searchConfig: t.searchConfig,
                    pageSize: t.pageSize,
                    pageIndex: t.pageIndex,
                    searchText: t.searchText
                };
            return n.length > 0 && tt(n), e.selectBySearchConfig(r).success(function(n) {
                t.searchData = n;
                o.formatPatients(t.searchData.items, {
                    birth: "ageStr",
                    status: "patientStatus"
                });
                nt();
                var r = {
                    total: t.searchData.totalCount,
                    data: t.searchData.items
                };
                i.resolve(r)
            }).error(function(n) {
                n.name == "ContainsIllegalCharactersException" && h.error("提示", "查询失败,检查搜索条件有非法字符!")
            }), i.promise
        },
        nt = function() {
            angular.forEach(t.searchData.items, function(n) {
                var i;
                n.doctorName && (i = _.find(t.doctorData, function(t) {
                    return t.id == n.doctorName
                }), n.doctorName = i ? i.name : "");
                n.lastDoctorName && (i = _.find(t.doctorData, function(t) {
                    return t.id == n.lastDoctorName
                }), n.lastDoctorName = i ? i.name : "")
            })
        },
        tt = function(n) {
            angular.forEach(n, function(n) {
                (n.field == "name" || n.field == "privateId") && (n.operator = "contains", n.field == "ageStr" && (n.field = "age"));
                var i = {};
                switch (n.operator) {
                    case "startswith":
                        i.code = n.field.trim();
                        i.value = n.value.trim();
                        i.comparator = "SS";
                        break;
                    case "endswith":
                        i.code = n.field.trim();
                        i.value = n.value.trim();
                        i.comparator = "ES";
                        break;
                    case "eq":
                        i.code = n.field.trim();
                        i.comparator = "=";
                        n.field == "firstVisitStr" ? (i.code = "firstVisit", i.value = moment(n.value).format("YYYY-MM-DD")) : i.value = n.value.trim();
                        n.field == "doctorName" && (i.code = "doctorId");
                        n.field == "sexStr" && (i.code = "sex");
                        n.field == "recordCreatedUserName" && (i.code = "recordcreateduser");
                        n.field == "ageStr" && (i.code = "Age");
                        break;
                    case "neq":
                        i.code = n.field.trim();
                        i.value = n.value.trim();
                        i.comparator = "!=";
                        break;
                    case "gte":
                        i.code = n.field.trim();
                        i.comparator = ">";
                        n.field == "firstVisitStr" ? (i.code = "firstVisit", i.value = moment(n.value).format("YYYY-MM-DD")) : i.value = n.value.trim();
                        break;
                    case "lte":
                        i.code = n.field.trim();
                        i.comparator = "<";
                        n.field == "firstVisitStr" ? (i.code = "firstVisit", i.value = moment(n.value).format("YYYY-MM-DD")) : i.value = n.value.trim();
                        break;
                    case "gt":
                        i.code = n.field.trim();
                        i.comparator = ">";
                        n.field == "firstVisitStr" ? (i.code = "firstVisit", i.value = moment(n.value).format("YYYY-MM-DD")) : i.value = n.value.trim();
                        break;
                    case "lt":
                        i.code = n.field.trim();
                        i.comparator = "<";
                        n.field == "firstVisitStr" ? (i.code = "firstVisit", i.value = moment(n.value).format("YYYY-MM-DD")) : i.value = n.value.trim();
                        break;
                    case "contains":
                        i.code = n.field.trim();
                        i.value = n.value.trim();
                        i.comparator = "C";
                        break;
                    case "doesnotcontain":
                        i.code = n.field.trim();
                        i.value = n.value.trim();
                        i.comparator = "!C"
                }
                i.code && i.comparator && t.searchConfig.searchCondFields.push(i)
            })
        };
    (function() {
        t.searchText = "";
        t.onSearch = g;
        d()
    })()
}]);
patientModule.controller("SearchPatientCtrl", ["$log", "$scope", "$modal", "appNav", "patientSvc", "formatUtil", "shortMessageUtil", "practiceSvc", "patientUtil", "aresNotification", "loginContext", "aresDialog", "dataDicSvc", function(n, t, i, r, u, f, e, o, s, h, c, l, a) {
    "use strict";
    var p = function(n) {
            t.pageIndex = n;
            t.pageChage = !0;
            y()
        },
        w = function(n, t) {
            e.sendMessage(n, t)
        },
        b = function(i) {
            s.deletePatient(i).then(function(r) {
                r == "deleted" || r == "archived" ? (s.removePatientFromPatientList(i, t.searchData.items), t.refreshGrid()) : n.error("Delete patient result is unkown.")
            })
        },
        k = function(n) {
            s.createFollowUpApptByPatientId(n).then(function() {
                h.success("预约成功")
            })
        },
        v = function() {
            o.getSearchConfigAll().success(function(n) {
                var i, r;
                t.searchConfigs = n;
                t.isDoctor && (i = _.find(t.searchConfigs, function(n) {
                    return n.name == "全部患者" && n.id == 0
                }), i && i.isPreferred && (i.isPreferred = !1, r = _.find(t.searchConfigs, function(n) {
                    return n.name == "我的患者"
                }), r.isPreferred = !0))
            })
        },
        d = function(n) {
            var r = null,
                u;
            n && (r = _.find(t.searchConfigs, function(t) {
                return t.id == n
            }));
            u = i.open({
                animation: !0,
                backdrop: "static",
                template: "<search-config-view><\/search-config-view>",
                controller: "SearchConfigCtrl",
                size: "lg",
                windowClass: "search-config-dialog",
                resolve: {
                    host: function() {
                        return {
                            searchConfig: r,
                            configNames: _.pluck(t.searchConfigs, "name")
                        }
                    }
                }
            });
            u.result.then(function(n) {
                var r = n,
                    i;
                n && (n.isDisposable ? n.id > 0 ? (i = _.find(t.searchConfigs, function(t) {
                    return t.id == n.id
                }), i.isDisposable = !0, r = i, r.id = 0) : t.searchConfigs.push(n) : (n.name == "我的患者" || n.name == "全部患者" ? i = _.find(t.searchConfigs, function(t) {
                    return t.name == n.name
                }) : n.id > 0 && (i = _.find(t.searchConfigs, function(t) {
                    return t.id == n.id
                })), i ? (i.id = n.id, i.name = n.name, i.isAscending = n.isAscending, i.orderByField = n.orderByField, i.searchCondFields = n.searchCondFields, i.searchResultFields = n.searchResultFields) : t.searchConfigs.push(n)), t.initSearchConfigDropDown(r), t.search())
            })
        },
        y = function() {
            t.searchConfig.isShowWeiXin = t.searchConfig.isShowWeiXin ? !0 : null;
            var n = {
                searchConfig: t.searchConfig,
                pageSize: t.pageSize,
                pageIndex: t.pageIndex,
                searchText: t.searchText
            };
            u.selectBySearchConfig(n).success(function(n) {
                t.searchData = n;
                f.formatPatients(t.searchData.items, {
                    birth: "ageStr",
                    status: "patientStatus"
                });
                g()
            }).error(function(n) {
                n.name == "ContainsIllegalCharactersException" && l.error("提示", "查询失败,检查搜索条件有非法字符!")
            })
        },
        g = function() {
            angular.forEach(t.searchData.items, function(n) {
                var i;
                n.doctorName && (t.doctors.length > 0 ? (i = _.find(t.doctors, function(t) {
                    return t.id == n.doctorName
                }), n.doctorName = i ? i.name : "") : a.doctorDic.loadActive().then(function(i) {
                    t.doctors = i;
                    var r = _.find(t.doctors, function(t) {
                        return t.id == n.doctorName
                    });
                    n.doctorName = r ? r.name : ""
                }));
                n.lastDoctorName && (t.doctors ? (i = _.find(t.doctors, function(t) {
                    return t.id == n.lastDoctorName
                }), n.lastDoctorName = i ? i.name : "") : a.doctorDic.loadActive().then(function(i) {
                    t.doctors = i;
                    var r = _.find(t.doctors, function(t) {
                        return t.id == n.lastDoctorName
                    });
                    n.lastDoctorName = r ? r.name : ""
                }))
            })
        };
    (function() {
        t.doctors = [];
        t.searchText = "";
        t.isDoctor = c.roleType == "牙医";
        t.pageIndex = 1;
        t.pageSize = 10;
        t.onPageChanged = p;
        t.sendMessage = w;
        t.deletePatient = b;
        t.createFollowUpAppt = k;
        t.openSearchConfigDialog = d;
        t.onSearch = y;
        t.initSearchConfigs = v;
        v()
    })()
}]);
patientModule.controller("PatientPhotoCtrl", ["$log", "$scope", "$modalInstance", "$timeout", "patientSvc", "membershipSvc", "dataDicSvc", "aresDialog", "loginContext", "host", function(n, t, i, r, u, f, e, o, s, h) {
    "use strict";
    var c = function(n) {
            n && u.getPictureById(n).success(function(n) {
                t.picture = n
            })
        },
        l = function() {
            t.closeCamera();
            i.close(t.picture)
        },
        a = function() {
            t.closeCamera();
            i.dismiss("cancel")
        },
        v = function() {
            t.picture = {}
        };
    (function() {
        t.patientId = h.patientId;
        t.picture = h.picture;
        t.isOnLoad = h.event == "load";
        t.cancel = a;
        t.save = l;
        t.initPicture = c;
        t.deletePicture = v
    })()
}]);
supplychainModule.directive("patientDrugOrderWorkflowView", ["$log", "$q", "$timeout", "$modal", "dataDicSvc", "eventAggregator", function(n, t, i) {
    return {
        replace: !0,
        templateUrl: "/app/patient/dialogs/patient-drug-order-workflow/patient-drug-order-workflow-view.html",
        link: function(n, t) {
            var r = function() {
                t.find("#drugOrderDetailGrid").kendoGrid({
                    dataSource: {
                        data: n.drugOrder.DrugOrderDetailList,
                        schema: {
                            model: {
                                id: "id",
                                fields: {
                                    DrugName: {
                                        type: "string",
                                        editable: !1
                                    },
                                    Specifications: {
                                        type: "string",
                                        editable: !1
                                    },
                                    Unit: {
                                        type: "string",
                                        editable: !1
                                    },
                                    Count: {
                                        type: "string",
                                        editable: !1
                                    },
                                    Usage: {
                                        type: "string",
                                        editable: !1
                                    }
                                }
                            }
                        }
                    },
                    editable: !1,
                    scrollable: !0,
                    sortable: {
                        mode: "single",
                        allowUnsort: !1
                    },
                    columns: [{
                        field: "DrugName",
                        title: "名称",
                        width: "130px"
                    }, {
                        field: "Specifications",
                        title: "规格",
                        width: "130px"
                    }, {
                        field: "Count",
                        title: "数量",
                        width: "100px"
                    }, {
                        field: "Unit",
                        title: "单位",
                        width: "100px"
                    }, {
                        field: "Usage",
                        title: "用法"
                    }]
                })
            };
            (function() {
                r();
                i(function() {
                    Ares.centerModal(t.closest(".modal-dialog"))
                }, 100)
            })()
        }
    }
}]);
supplychainModule.controller("PatientDrugOrderWorkflowCtrl", ["$log", "$q", "$filter", "$timeout", "$scope", "enums", "$modalInstance", "host", "dataDicSvc", "systemConfigUtil", "officeOptionSvc", function(n, t, i, r, u, f, e, o) {
    "use strict";
    var s = function() {
        e.dismiss()
    };
    (function() {
        u.drugOrder = o.drugOrder;
        u.clean = s
    })()
}]);
patientModule.directive("patientPlanDetailEditView", ["$log", "$timeout", "$window", function(n, t) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/dialogs/patient-plan-detail-edit/patient-plan-detail-edit-view.html",
        link: function(n, i) {
            (function() {
                t(function() {
                    Ares.centerModal(i.closest(".modal-dialog"))
                }, 100)
            })()
        }
    }
}]);
patientModule.controller("PatientPlanDetailEditCtrl", ["$log", "$scope", "$q", "$modalInstance", "host", "membershipSvc", "aresNotification", function(n, t, i, r, u, f, e) {
    "use strict";
    var o = function() {
            r.close()
        },
        s = function() {
            t.planType == "giftPlan" && (t.title = "编辑回馈方案明细")
        },
        h = function() {
            var u, f, n;
            t.isSaving = !0;
            u = t.originalDetail.remainCount;
            f = t.detail.remainCount;
            u == f && (e.info("请编辑明细"), t.isSaving = !1);
            n = [];
            t.planType == "discountPlan" ? n.push(c()) : n.push(l());
            i.all(n).then(function() {
                e.success("编辑成功");
                r.close(t.detail)
            }, function() {
                e.error("编辑失败");
                t.isSaving = !1
            })
        },
        c = function() {
            var r = i.defer(),
                n = u.detail,
                e = {
                    patientId: u.patient.id,
                    membershipId: u.membership.id,
                    membershipTypeId: u.membership.membershipTypeId,
                    discountPlanId: u.membershipType.discountPlan.id,
                    details: []
                };
            return e.details.push({
                discountPlanDetailId: n.id,
                itemName: n.itemName,
                detailType: n.detailType,
                chargeItemId: n.itemId,
                oldRemainCount: t.originalDetail.remainCount,
                newRemainCount: n.remainCount
            }), f.updatePatientMembershipDiscountPlan(e).then(function() {
                r.resolve()
            }, function() {
                r.reject()
            }), r.promise
        },
        l = function() {
            var r = i.defer(),
                n = u.detail,
                e = {
                    patientId: u.patient.id,
                    patientName: u.patient.name,
                    membershipId: u.membership.id,
                    details: []
                };
            e.details.push({
                itemName: n.itemName,
                itemId: n.itemId,
                oldRemainCount: t.originalDetail.remainCount,
                newRemainCount: n.remainCount
            });
            f.updatePatientMembershipGiftPlan(e).then(function() {
                r.resolve()
            }, function() {
                r.reject()
            })
        },
        a = function(n) {
            var r = n.sender,
                u = r.value(),
                i;
            u == null ? (r.value(1), t.detail.remainCount = 1) : (i = t.originalDetail.maxCount, u > i && (r.value(i), t.detail.remainCount = i))
        };
    (function() {
        t.title = "编辑折扣方案明细";
        t.originalDetail = angular.copy(u.detail);
        t.detail = u.detail;
        t.planType = u.planType;
        t.cancel = o;
        t.save = h;
        t.onRemainCountChange = a;
        s()
    })()
}]);
patientModule.directive("patientTagManageView", ["$log", "$timeout", "$window", function(n, t) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/dialogs/patient-tag-manage/patient-tag-manage-view.html",
        link: function(n, i) {
            (function() {
                t(function() {
                    Ares.centerModal(i.closest(".modal-dialog"))
                }, 100)
            })()
        }
    }
}]);
patientModule.controller("PatientTagManageCtrl", ["$log", "$scope", "$modalInstance", function(n, t, i) {
    "use strict";
    var r = function() {
        i.close()
    };
    (function() {
        t.close = r
    })()
}]);
patientModule.directive("disposalDialogView", ["$log", "$timeout", "$window", "dataDicSvc", function(n, t, i, r) {
    "use strict";
    return {
        replace: !0,
        templateUrl: "/app/patient/views/disposal-dialog-view.html",
        link: function(n, t) {
            var h = Ares.kendoGridUtil(i, n),
                s = !1,
                u = null,
                f, e, o;
            r.diagnoseItemDic.load();
            n.isSelect = !1;
            f = function() {
                if (n.disposalItemList) {
                    s = !0;
                    var i = t.find("#disposalItemList");
                    u = i.kendoGrid({
                        dataSource: {
                            data: n.disposalItemList
                        },
                        scrollable: !1,
                        sortable: !0,
                        selectable: "single",
                        columns: [{
                            field: "itemCode",
                            title: "项目编码",
                            width: "140px",
                            headerAttributes: {
                                style: "text-align: center; font-size: 14px; font-weight: bolder;"
                            }
                        }, {
                            field: "itemName",
                            title: "名称",
                            width: "300px",
                            headerAttributes: {
                                style: "text-align: center; font-size: 14px; font-weight: bolder;"
                            }
                        }, {
                            field: "itemEnName",
                            title: "英文名",
                            width: "60x",
                            headerAttributes: {
                                style: "text-align: center; font-size: 14px; font-weight: bolder;"
                            }
                        }, {
                            field: "pinyin",
                            title: "拼音",
                            width: "100px",
                            headerAttributes: {
                                style: "text-align: center; font-size: 14px; font-weight: bolder;"
                            }
                        }, ],
                        change: function() {
                            n.isSelect = !0
                        }
                    }).data("kendoGrid")
                }
            };
            e = function() {
                var t = u.select(),
                    i = $("tr", u.tbody).index(t);
                n.save2(n.disposalItemList[i])
            };
            $("#disposalItemList").on("dblclick", "tr.k-state-selected", function() {
                var t = u.select(),
                    i = $("tr", u.tbody).index(t);
                n.save2(n.disposalItemList[i])
            });
            o = function() {
                    var f, e, i, t;
                    if (n.searchString == "" || n.searchString == undefined) {
                        n.disposalItemList = r.diagnoseItemDic.data();
                        u && u.dataSource.data(n.disposalItemList);
                        return
                    }
                    for (f = [], e = r.diagnoseItemDic.data(), i = 0; i < e.length; i++) t = e[i], t.itemName = t.itemName || "", t.itemCode = t.itemCode || "", t.itemEnName = t.itemEnName || "", t.pinyin = t.pinyin || "", (t.itemName.toLowerCase().indexOf(n.searchString.toLowerCase()) > -1 || t.itemCode.toLowerCase().indexOf(n.searchString.toLowerCase()) > -1 || t.itemEnName.toLowerCase().indexOf(n.searchString.toLowerCase()) > -1 || t.pinyin.toLowerCase().indexOf(n.searchString.toLowerCase()) > -1) && f.push(t);
                    n.disposalItemList = {};
                    n.disposalItemList = f;
                    u.dataSource.data(n.disposalItemList)
                },
                function() {
                    n.save = e;
                    n.$watch("disposalItemList", function() {
                        f()
                    });
                    n.$watch("searchString", function() {
                        o()
                    })
                }()
        }
    }
}]);
patientModule.directive("groupPatientConsultRecordView", ["loginContext", function(n) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "GroupPatientConsultRecordCtrl",
        templateUrl: "/app/patient/views/group-patient-consult-record-view.html",
        scope: {
            patientId: "="
        },
        link: function(t, i) {
            var r = function(n) {
                    i.find(n.target).attr("class", "second-level-button-hover-class")
                },
                u = function(n) {
                    i.find(n.target).attr("class", "second-level-button-default-class")
                },
                f = function(n) {
                    i.find(n.target).attr("class", "third-level-button-hover-class")
                },
                e = function(n) {
                    i.find(n.target).attr("class", "third-level-button-default-class")
                };
            (function() {
                t.providerJob = n.providerJob;
                t.addMouseHoverClass = r;
                t.removeMouseHoverClass = u;
                t.addThirdLevelMouseHoverClass = f;
                t.removeThirdLevelMouseHoverClass = e
            })()
        }
    }
}]);
patientModule.directive("instrumentPackageUseRecordView", ["loginContext", "enums", function(n, t) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "InstrumentPackageUseRecordCtrl",
        templateUrl: "/app/patient/views/instrument-package-use-record-view.html",
        scope: {
            patientId: "="
        },
        link: function(n) {
            var r = function() {
                    var t = moment().add(-7, "day").format("YYYY-MM-DD"),
                        i = moment().format("YYYY-MM-DD");
                    n.startTime = t;
                    n.endTime = moment(i).add(1, "day").format("YYYY-MM-DD");
                    n.timeSpan = {
                        startDate: t,
                        endDate: i
                    }
                },
                u = function(t) {
                    t = t || n.timeSpan;
                    n.startTime = moment(t.startDate).format("YYYY-MM-DD");
                    n.endTime = moment(t.endDate).add(1, "day").format("YYYY-MM-DD");
                    i()
                },
                f = function() {
                    return {
                        patientId: n.patientId,
                        usingTimeStartDate: n.startTime,
                        usingTimeEndDate: n.endTime,
                        containerCode: n.containerCode
                    }
                },
                i = function() {
                    var t = f();
                    n.getPackageInstanceUseList(t)
                },
                e = function() {
                    r();
                    i()
                };
            (function() {
                n.packageUsedStatus = t.CssdPackageStatus.Used;
                n.containerCode = "";
                n.onDateRangeChanged = u;
                n.searchLog = i;
                e()
            })()
        }
    }
}]);
patientModule.directive("patientAdminRecordView", ["$log", "$timeout", "$interval", "$window", "$modal", "dataDicSvc", "appNav", "patientSvc", function(n, t, i, r, u, f, e, o) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "PatientAdminRecordCtrl",
        templateUrl: "/app/patient/views/patient-admin-record-view.html",
        scope: {
            patientId: "="
        },
        link: function(n, t) {
            r.PatientCtrl_goToPatient = function(n) {
                var t = $(n).closest("tr"),
                    i = $("#PatientRelation").data("kendoGrid"),
                    r = i.dataItem(t);
                return e.goToPatient(r.patientId), !1
            };
            f.medicineDic.load().then(function(t) {
                n.medicines = t
            });
            var c = function() {
                    var t = u.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<patient-referee-detail-view><\/patient-referee-detail-view>",
                        controller: "PatientRefereeDetailCtrl",
                        size: "lg",
                        resolve: {
                            host: function() {
                                return {
                                    patient: n.patient
                                }
                            }
                        }
                    })
                },
                l = function() {
                    n.patient.refereeId > 0 && o.getPatient(n.patient.refereeId).success(function(t) {
                        n.toPatient = t;
                        e.goToPatient(n.toPatient.id)
                    })
                },
                s = !0;
            n.initList = function() {
                if (n.patientRelation) {
                    var i = $(t).find("#PatientRelation");
                    s = !1;
                    i.kendoGrid({
                        dataSource: n.patientRelation,
                        scrollable: !1,
                        sortable: !0,
                        selectable: "single",
                        columns: [{
                            field: "relationType",
                            title: "关系",
                            width: "100px"
                        }, {
                            field: "patientName",
                            title: "关系人姓名",
                            width: "150px",
                            template: kendo.template($("#patientNameTemplate").html())
                        }, {
                            field: "sex",
                            title: "性别",
                            width: "100px"
                        }, {
                            field: "mobile",
                            title: "手机",
                            width: "100x"
                        }, {
                            field: "membershipType",
                            title: "会员卡类型",
                            width: "160px"
                        }, {
                            field: "cardNumber",
                            title: "会员卡账号",
                            width: "150px"
                        }, {
                            field: "relationMark",
                            title: "备注",
                            width: "100px"
                        }, ]
                    })
                }
            };
            var h = function() {
                    var i = null,
                        t, r;
                    if (!i)
                        for (t = n.$parent, r = 0; r < 10; r++)
                            if (t == null || t.patientTabManager) {
                                i = t;
                                break
                            } else t = t.$parent;
                    return i
                },
                a = function(n, t) {
                    o.updateAdvisor(n.id, t);
                    n.advisorId = t
                },
                v = function(n) {
                    o.undoAdvisor(n.id);
                    n.advisorId = null
                };
            (function() {
                n.showReferee = c;
                n.gotoPatient = l;
                n.findPatientTabManagerScope = h;
                n.cancelAdvisor = v;
                n.updateAdvisor = a;
                var t = i(function() {
                    var t = h();
                    t && t.patientTabManager.activeTab && t.patientTabManager.activeTab.patient && t.patientTabManager.activeTab.patient.marketCenterAccount && (n.patient.marketCenterAccount = t.patientTabManager.activeTab.patient.marketCenterAccount)
                }, 1e3);
                n.$watch("patientRelation", function() {
                    s && n.initList()
                });
                n.$on("$destroy", function() {
                    delete r.PatientCtrl_goToPatient;
                    t && i.cancel(t)
                })
            })()
        }
    }
}]);
patientModule.directive("patientApptRecordView", ["$log", "$timeout", "enums", "patientSvc", "appNav", "$state", "loginContext", "permissionProvider", "aresDialog", function(n, t, i, r, u, f, e) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "PatientApptRecordCtrl",
        templateUrl: "/app/patient/views/patient-appt-record-view.html",
        scope: {
            patientId: "="
        },
        link: function(n) {
            var i = function(i, f) {
                    i == "hardTissue" ? (t(function() {
                        r("patientgeneralMedicalRecords.patientGeneralExam.view", {
                            patientId: n.patientId,
                            examId: f
                        })
                    }, 200), u.goToHardTissue(n.patientId)) : i == "emr" ? u.goToEMR(n.patientId) : i == "imaging" ? u.goToImaging(n.patientId, "imagingHistory", {
                        apptId: f
                    }) : i == "prescription" ? u.goToPrescription(n.patientId) : i == "patientDocument" ? u.goToPatientDocument(n.patientId, "patientDocumentHistory", {
                        apptId: f
                    }) : i == "outprocess" ? u.goToOutprocess(n.patientId) : i == "patientCharge" ? u.goToCharge(n.patientId, f) : i == "orthdontic" && u.goToOrthdonticProcess(n.patientId)
                },
                r = function(n, t) {
                    f.transitionTo(n, t, {})
                };
            (function() {
                n.goToTab = i;
                n.isAdminOffice = e.isAdminOffice
            })()
        }
    }
}]);
patientModule.directive("patientBatchEditView", ["$log", "$window", "$timeout", "$q", "$modal", "dataDicSvc", function(n, t, i, r, u, f) {
    "use strict";
    return {
        templateUrl: "/app/patient/views/patient-batch-edit-view.html",
        link: function(n, u) {
            var s = [{
                    field: "name",
                    title: "名称",
                    width: "120px"
                }, {
                    field: "mobile",
                    title: "手机号",
                    width: "120px"
                }, {
                    field: "privateId",
                    title: "病历号",
                    width: "120px"
                }, {
                    field: "sourceLevel1",
                    title: "患者来源",
                    width: "220px",
                    template: function(n) {
                        var t = "";
                        return n.sourceLevel1 ? (t += n.sourceLevel1 ? n.sourceLevel1 : "", t += n.sourceLevel1 && n.sourceLevel2 ? ">" : "", t += n.sourceLevel2 ? n.sourceLevel2 : "", t += n.sourceLevel1 && n.sourceLevel2 && n.sourceLevel3 ? ">" : "", t += n.sourceLevel3 ? n.sourceLevel3 : "") : n.sourceTypeOne && (t += n.sourceTypeOne ? n.sourceTypeOne : "", t += n.sourceTypeOne && n.sourceTypeTwo ? ">" : "", t += n.sourceTypeTwo ? n.sourceTypeTwo : "", t += n.sourceTypeOne && n.sourceTypeTwo && n.sourceTypeThree ? ">" : "", t += n.sourceTypeThree ? n.sourceTypeThree : ""), t
                    }
                }, {
                    field: "sexStr",
                    title: "性别",
                    width: "120px"
                }, {
                    field: "ageStr",
                    title: "年龄",
                    width: "120px"
                }, {
                    field: "officeName",
                    title: "所属诊所",
                    width: "120px"
                }],
                h, c = function(n) {
                    i(function() {
                        var e = angular.copy(s),
                            i = u.find("#patientList"),
                            r, f;
                        i.html("");
                        r = i.offset().top;
                        f = t.innerHeight - r - 60;
                        h = i.kendoGrid({
                            dataSource: {
                                data: n
                            },
                            height: f,
                            model: {
                                id: "id"
                            },
                            scrollable: !0,
                            columns: e,
                            sortable: !1,
                            resizable: !0,
                            reorderable: !0,
                            columnMenu: !1
                        }).data("kendoGrid")
                    })
                },
                l = function() {
                    var t = r.defer();
                    return f.patientSourceTypeDic.load().then(function(i) {
                        n.patientSourceType = i;
                        a(i);
                        t.resolve()
                    }), t.promise
                },
                a = function(t, i) {
                    for (var f, s, h, c, o = [], r = 0; r < t.length; r++) t[r].level == 1 && t[r].isDisabled === !1 && o.push(t[r]);
                    f = {
                        sourceName: ""
                    };
                    i && (f = _.find(t, function(n) {
                        return n.id == i.parentId
                    }));
                    s = u.find("#parentSourceType");
                    h = {
                        sourceName: ""
                    };
                    o.splice(0, 0, h);
                    c = s.kendoDropDownList({
                        dataSource: o,
                        dataTextField: "sourceName",
                        dataValueField: "sourceName",
                        value: f.sourceName,
                        select: function(t) {
                            var i = this.dataItem(t.item) || null;
                            n.patient.sourceTypeLevel1 = i.sourceName;
                            n.patient.sourceType = "";
                            n.patient.refereeName = "";
                            e(i.id)
                        }
                    }).data("kendoDropDownList");
                    f.sourceName ? e(f.id) : (n.hasParentSource = !1, n.patient.hasParentSource = !1)
                },
                e = function(t) {
                    var r, i, s, f;
                    for (t ? (n.hasParentSource = !0, n.patient.hasParentSource = !0) : (n.hasParentSource = !1, n.patient.hasParentSource = !1), r = [], i = 0; i < n.patientSourceType.length; i++) n.patientSourceType[i].parentId == t && n.patientSourceType[i].isDisabled === !1 && r.push(n.patientSourceType[i]);
                    var e = u.find("#sourceType"),
                        h = n.patient;
                    r.splice(0, 0, {
                        sourceName: ""
                    });
                    s = e.kendoDropDownList({
                        dataSource: r,
                        dataTextField: "sourceName",
                        dataValueField: "sourceName",
                        value: n.patient.sourceType,
                        select: function(t) {
                            n.patient.sourceType = this.dataItem(t.item)[this.options.dataValueField] || null;
                            n.patient.refereeId = null;
                            n.patient.refereeName = null;
                            n.patient.refereeMobileOrCode = null;
                            n.patient.sourceType == "朋友介绍" ? (n.enableReferee = !0, n.enableProvider = !1, n.enableOtherSourceType = !1) : n.patient.sourceType == "员工介绍" ? (n.enableProvider = !0, n.enableReferee = !1, n.enableOtherSourceType = !1) : n.patient.sourceType ? (n.enableReferee = !1, n.enableProvider = !1, n.enableOtherSourceType = !0, n.hasSourceType = !0) : (n.enableReferee = !1, n.enableProvider = !1, n.enableOtherSourceType = !1, n.hasSourceType = !1);
                            n.hasSourceType = !0;
                            o(this.dataItem(t.item))
                        }
                    }).data("kendoDropDownList");
                    f = _.find(n.patientSourceType, function(t) {
                        return t.sourceName == n.patient.sourceType && t.level == 2
                    });
                    f && o(f)
                },
                o = function(t) {
                    for (var e, o, r = n.patient.refereeName ? n.patient.refereeName : "", s = r != "" ? r.split(",") : [], f = [], i = 0; i < n.patientSourceType.length; i++) n.patientSourceType[i].parentId == t.id && n.patientSourceType[i].isDisabled === !1 && f.push(n.patientSourceType[i]);
                    e = {
                        sourceName: ""
                    };
                    f.splice(0, 0, e);
                    o = u.find("#otherSourceType").kendoDropDownList({
                        dataSource: f,
                        dataTextField: "sourceName",
                        dataValueField: "sourceName",
                        value: r,
                        select: function(t) {
                            var i = this.dataItem(t.item) || null;
                            n.patient.refereeName = i.sourceName
                        }
                    }).data("kendoDropDownList")
                },
                v = function() {
                    f.allProviderDic.loadActive().then(function(t) {
                        var f, r;
                        n.providers = t;
                        f = u.find("#provider").kendoNameCodeFilterDropDownList({
                            dataSource: n.providers,
                            filter: "contains",
                            placeholder: "请选择推荐人",
                            dataTextField: "name",
                            dataValueField: "id",
                            value: n.patient.refereeId || null,
                            select: function(t) {
                                n.patient.refereeId = this.dataItem(t.item)[this.options.dataValueField] || 0;
                                i(function() {
                                    var t = _.find(n.providers, function(t) {
                                        return t.id == n.patient.refereeId
                                    });
                                    n.patient.refereeName = t ? t.name : "";
                                    n.patient.refereeMobileOrCode = t ? t.mobile : ""
                                })
                            }
                        }).data("kendoNameCodeFilterDropDownList");
                        n.providers && n.providers.length > 0 && (r = n.providers[0], n.patient.refereeId = r.id, n.patient.refereeName = r ? r.name : "", n.patient.refereeMobileOrCode = r ? r.mobile : "")
                    })
                },
                y = function() {
                    var t = r.defer();
                    return f.attendantDic.loadActive().then(function(i) {
                        var r = $(u).find("#attendantInput");
                        n.patient != undefined && r.kendoDropDownList({
                            dataSource: i,
                            optionLabel: "未指定客服",
                            filter: "contains",
                            dataTextField: "name",
                            dataValueField: "id",
                            value: n.patient.attendantId,
                            select: function(t) {
                                n.patient.attendantId = this.dataItem(t.item)[this.options.dataValueField] || null
                            }
                        });
                        t.resolve()
                    }), t.promise
                },
                p = function(t) {
                    n.patient.refereeName = t.name;
                    n.patient.refereeMobileOrCode = t.mobile;
                    n.patient.refereeId = t.id
                },
                w = function() {
                    n.patient.refereeName = null;
                    n.patient.refereeMobileOrCode = null;
                    n.patient.refereeId = null
                };
            (function() {
                n.patient = {};
                n.onPatientChanged = p;
                n.onPatientCleared = w;
                l().then(function() {
                    y().then(function() {
                        c(n.patients)
                    })
                });
                n.$watch("patient.sourceType", function() {
                    n.patient != null && (n.enableReferee = n.patient.sourceType == "朋友介绍" ? !0 : !1, n.patient.sourceType == "员工介绍" ? (n.enableProvider = !0, v()) : n.enableProvider = !1, n.enableOtherSourceType = n.patient.sourceType && n.patient.sourceType != "朋友介绍" && n.patient.sourceType != "员工介绍" ? !0 : !1)
                })
            })()
        }
    }
}]);
patientModule.directive("patientChoiceChargeView", ["$log", "$timeout", "$modal", "practiceSvc", "patientSvc", "appointmentSvc", "loginContext", function() {
    "use strict";
    return {
        templateUrl: "/app/patient/views/patient-choice-charge-view.html",
        controller: "PatientChoiceChargeCtrl",
        link: function() {
            (function() {})()
        }
    }
}]);
patientModule.directive("patientConsultRecordView", ["$log", "$modal", "$timeout", "enums", "patientSvc", "appNav", "$state", "$location", function(n, t, i, r, u, f, e, o) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "PatientConsultRecordCtrl",
        templateUrl: "/app/patient/views/patient-consult-record-view.html",
        scope: {
            patientId: "="
        },
        link: function(n) {
            var i = function() {
                    var i = t.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<patient-weixin-consult-view><\/patient-weixin-consult-view>",
                        controller: "patientWeixinConsultCtrl",
                        size: "lg",
                        windowClass: "weixin-chat-record-dialog",
                        resolve: {
                            host: function() {
                                return {
                                    patientId: n.patientId
                                }
                            }
                        }
                    })
                },
                r = function() {
                    var t = o.search() || {};
                    t.isShowPopup && n.createConsult()
                };
            (function() {
                n.showWeixinRecord = i;
                n.initCreateConsultRecord = r
            })()
        }
    }
}]);
patientModule.directive("patientDashboard", ["$log", "$timeout", "$state", "$modal", "appNav", "enums", "eventAggregator", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/views/patient-dashboard.html",
        controller: ["$scope", function() {
            (function() {})()
        }],
        scope: {
            officeId: "="
        },
        link: function() {
            (function() {})()
        }
    }
}]);
patientModule.directive("patientDiagnoseRecordView", ["$log", "$timeout", "enums", "patientSvc", "appNav", "$state", "sessionCache", function(n, t, i, r, u, f, e) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "PatientDiagnoseRecordCtrl",
        templateUrl: "/app/patient/views/patient-diagnose-record-view.html",
        scope: {
            patientId: "="
        },
        link: function(n) {
            var i = e.getCache(e.keys.PatientDiagnoseRecordState),
                r = function() {
                    var n = $(".patient-content-container").scrollTop(),
                        t = {
                            top: n
                        };
                    i.saveObject(t)
                },
                u = function() {
                    var n = i.loadObject(),
                        r = n && n.top ? n.top : null;
                    t(function() {
                        r && $(".patient-content-container").scrollTop(r)
                    }, 1e3)
                };
            (function() {
                n.savePageState = r;
                n.setPageState = u
            })()
        }
    }
}]);
patientModule.directive("patientDrugDictConfig", ["$log", "$timeout", "dataDicSvc", "patientSvc", "practiceSvc", "aresDialog", function(n, t, i, r, u, f) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/views/patient-drug-dict-config.html",
        link: function(n, i) {
            n.dictGridMode = {};
            var o = function() {},
                r = function(t) {
                    var h, r, e, o, s;
                    if (t.preventDefault(), h = i.find("#drugItemEditGrid").data("kendoGrid"), n.dictGridMode == "edit") {
                        if (r = this.dataItem($(t.currentTarget).closest("tr")), r.drugName == null || r.drugName == "" || r.specifications == null || r.specifications == "" || r.usage == null || r.usage == "") {
                            f.warn("信息", "名称，规格及用法不能为空，请先填写再保存！");
                            return
                        }
                        if (r.id) {
                            for (e = null, o = 0; o < n.durgDict.length; ++o)
                                if (r.id == n.durgDict[o].id) {
                                    e = angular.copy(n.durgDict[o]);
                                    e.drugName = r.drugName;
                                    e.pinyin = r.pinyin;
                                    e.count = r.count;
                                    e.unit = r.unit;
                                    e.specifications = r.specifications;
                                    e.usage = r.usage;
                                    e.price = r.price;
                                    break
                                }
                            if (e == null) return;
                            u.updateDrugOrderDetail(e).success(function() {
                                for (var t = 0; t < n.durgDict.length; ++t)
                                    if (n.durgDict[t].id == r.id) {
                                        n.durgDict[t].drugName = r.drugName;
                                        n.durgDict[t].pinyin = r.pinyin;
                                        n.durgDict[t].count = r.count;
                                        n.durgDict[t].unit = r.unit;
                                        n.durgDict[t].specifications = r.specifications;
                                        n.durgDict[t].usage = r.usage;
                                        n.durgDict[t].price = r.price;
                                        break
                                    }
                            })
                        } else r.did = 0, r.id = 0, u.createDrugOrderDetail(r).success(function(t) {
                            r.id = t.id;
                            n.durgDict.push(t)
                        });
                        s = i.find("#drugItemEditGrid").data("kendoGrid");
                        s.saveRow();
                        n.dictGridMode = "browser"
                    } else s = i.find("#drugItemEditGrid").data("kendoGrid"), s.editRow($(t.currentTarget).closest("tr")), n.dictGridMode = "edit"
                },
                e = function(t) {
                    var f, r;
                    if (t.preventDefault(), n.dictGridMode == "edit") {
                        f = i.find("#drugItemEditGrid").data("kendoGrid");
                        f.cancelRow();
                        n.dictGridMode = "browser";
                        return
                    }
                    r = this.dataItem($(t.currentTarget).closest("tr"));
                    u.deleteDrugOrderDetail(r.id).success(function() {
                        var u = i.find("#drugItemEditGrid").data("kendoGrid"),
                            t;
                        for (u.dataSource.remove(r), t = 0; t < n.durgDict.length; ++t)
                            if (n.durgDict[t].id == r.id) {
                                n.durgDict.splice(t, 1);
                                break
                            }
                    })
                };
            (function() {
                var t = new kendo.data.DataSource({
                        data: n.durgDict,
                        schema: {
                            model: {
                                id: "id",
                                fields: {
                                    drugName: {
                                        type: "string",
                                        validation: {
                                            required: !0
                                        }
                                    },
                                    specifications: {
                                        type: "string",
                                        validation: {
                                            required: !0,
                                            drugnamevalidation: function(n) {
                                                return n.is("[name='specifications']") && n.val() == "" ? (n.attr("data-drugnamevalidation-msg", "规格不能为空"), !1) : !0
                                            }
                                        }
                                    },
                                    unit: {
                                        type: "string"
                                    },
                                    count: {
                                        type: "number",
                                        validation: {
                                            required: !0,
                                            min: 0
                                        }
                                    },
                                    usage: {
                                        type: "string",
                                        validation: {
                                            required: !0,
                                            drugnamevalidation: function(n) {
                                                return n.is("[name='usage']") && n.val() == "" ? (n.attr("data-drugnamevalidation-msg", "用法不能为空"), !1) : !0
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }),
                    u;
                n.dictGridMode = "browser";
                i.find("#drugItemEditGrid").kendoGrid({
                    dataSource: t,
                    height: 550,
                    scrollable: !0,
                    selectable: "single",
                    sortable: {
                        mode: "single",
                        allowUnsort: !1
                    },
                    edit: function() {
                        n.dictGridMode = "edit"
                    },
                    save: function() {
                        n.dictGridMode = "browser"
                    },
                    toolbar: [{
                        name: "create",
                        text: "新建"
                    }],
                    columns: [{
                        field: "drugName",
                        title: "名称",
                        width: "130px"
                    }, {
                        field: "specifications",
                        title: "规格",
                        width: "130px"
                    }, {
                        field: "count",
                        title: "数量",
                        width: "100px"
                    }, {
                        field: "unit",
                        title: "单位",
                        width: "100px"
                    }, {
                        field: "price",
                        title: "单价",
                        width: "100px"
                    }, {
                        field: "usage",
                        title: "用法"
                    }, {
                        command: [{
                            text: "更新",
                            click: r
                        }, {
                            text: "删除",
                            click: e
                        }],
                        title: "操作",
                        width: "220px"
                    }],
                    editable: "inline"
                });
                u = i.find("#drugItemEditGrid").data("kendoGrid");
                n.ok = o;
                n.updateDictItem = r;
                n.deleteDictItem = e
            })();
            t(function() {
                Ares.centerModal(i.closest(".modal-dialog"))
            }, 5)
        }
    }
}]);
patientModule.directive("patientDrugorderEditView", ["$log", "$timeout", "practiceSvc", "appointmentSvc", "aresDialog", "loginContext", function(n, t, i) {
    "use strict";
    return {
        templateUrl: "/app/patient/views/patient-drugorder-edit-view.html",
        controller: "PatientDrugOrderEditCtrl",
        link: function(n, r) {
            var u = null;
            n.deleteFromDurgOrder = function(t) {
                var r, i;
                if (t.preventDefault(), n.isEdit)
                    for (r = this.dataItem($(t.currentTarget).closest("tr")), i = 0; i < n.currentDrugOrder.drugOrderDetailList.length; ++i)
                        if (n.currentDrugOrder.drugOrderDetailList[i].id == r.id) {
                            n.currentDrugOrder.drugOrderDetailList.splice(i, 1);
                            n.updateDrugOrderGridDataSource(n.currentDrugOrder.drugOrderDetailList);
                            break
                        }
            };
            n.updateDrugDictGridDataSource = function() {
                var t = $(r).find("#drugBasicDictionaryGrid").data("kendoGrid"),
                    i = new kendo.data.DataSource({
                        data: n.data.durgDict,
                        schema: {
                            model: {
                                id: "id",
                                fields: {
                                    drugName: {
                                        type: "string"
                                    },
                                    specifications: {
                                        type: "string"
                                    },
                                    unit: {
                                        type: "string"
                                    },
                                    count: {
                                        type: "number"
                                    },
                                    usage: {
                                        type: "string"
                                    }
                                }
                            }
                        }
                    });
                t.setDataSource(i)
            };
            n.addToDrugOrder = function(i) {
                var f = this;
                u && t.cancel(u);
                u = t(function() {
                    var u;
                    i.preventDefault();
                    var o = $(r).find("#drugBasicDictionaryGrid").data("kendoGrid"),
                        t = f.dataItem($(i.currentTarget).closest("tr")),
                        e = {
                            id: n.data.idRoot - 1,
                            drugName: t.drugName,
                            specifications: t.specifications,
                            unit: t.unit,
                            count: t.count,
                            usage: t.usage,
                            did: t.id,
                            price: t.price
                        };
                    n.data.idRoot = n.data.idRoot - 1;
                    u = !1;
                    angular.forEach(n.currentDrugOrder.drugOrderDetailList, function(n) {
                        n.did != e.did || u || (n.count = n.count + e.count, u = !0)
                    });
                    u || n.currentDrugOrder.drugOrderDetailList.push(e);
                    n.updateDrugOrderGridDataSource(n.currentDrugOrder.drugOrderDetailList)
                }, 150)
            };
            i.listDurgBasicDictionary().success(function(i) {
                n.data.durgDict = i;
                e();
                n.data.idRoot = -1;
                var o = r.find("#drugBasicDictionaryGrid");
                if (!o.hasClass("disabled")) o.on("dblclick", "tr.k-state-selected", function(i) {
                    i.preventDefault();
                    var f = this;
                    u && t.cancel(u);
                    u = t(function() {
                        var e = $(r).find("#drugBasicDictionaryGrid").data("kendoGrid"),
                            t = e.dataItem($(f)),
                            u = {
                                id: n.data.idRoot - 1,
                                drugName: t.drugName,
                                specifications: t.specifications,
                                unit: t.unit,
                                count: t.count,
                                usage: t.usage,
                                did: t.id
                            },
                            i;
                        n.data.idRoot = n.data.idRoot - 1;
                        i = !1;
                        angular.forEach(n.currentDrugOrder.drugOrderDetailList, function(n) {
                            n.did != u.did || i || (n.count = n.count + u.count, i = !0)
                        });
                        i || n.currentDrugOrder.drugOrderDetailList.push(u);
                        n.updateDrugOrderGridDataSource(n.currentDrugOrder.drugOrderDetailList)
                    }, 150)
                });
                f(null, !0)
            });
            var e = function() {
                    $(r).find("#drugBasicDictionaryGrid").kendoGrid({
                        dataSource: {
                            data: n.data.durgDict,
                            schema: {
                                model: {
                                    id: "id",
                                    fields: {
                                        drugName: {
                                            type: "string"
                                        },
                                        specifications: {
                                            type: "string"
                                        },
                                        unit: {
                                            type: "string"
                                        },
                                        count: {
                                            type: "number"
                                        },
                                        usage: {
                                            type: "string"
                                        }
                                    }
                                }
                            }
                        },
                        dataBound: function() {
                            var t = this;
                            r.find(".btn-add-detail").click(function(i) {
                                n.addToDrugOrder.call(t, i)
                            })
                        },
                        height: 220,
                        scrollable: !0,
                        selectable: "single",
                        sortable: {
                            mode: "single",
                            allowUnsort: !1
                        },
                        columns: [{
                            field: "drugName",
                            title: "名称",
                            width: "130px"
                        }, {
                            field: "specifications",
                            title: "规格",
                            width: "130px"
                        }, {
                            field: "count",
                            title: "数量",
                            width: "100px"
                        }, {
                            field: "price",
                            title: "单价",
                            width: "100px"
                        }, {
                            field: "unit",
                            title: "单位",
                            width: "100px"
                        }, {
                            field: "usage",
                            title: "用法"
                        }, {
                            command: [{
                                text: "添加",
                                template: function() {
                                    return n.isEdit ? '<input type="button" class="lc-btn lc-btn-default default-btn btn-add-detail" value="添加" />' : '<input type="button" class="lc-btn lc-btn-default default-btn" value="添加" disabled="disabled"/>'
                                }
                            }],
                            title: "操作",
                            width: "120px"
                        }]
                    })
                },
                h = function() {
                    var t, f, h, e, u, o, s;
                    if (!n.currentDrugOrder || !n.oldDrugOrder) return !1;
                    t = $(r).find("#doctor").data("kendoNameCodeFilterComboBox");
                    t && t.value() && (n.currentDrugOrder.doctorName = t.text(), n.currentDrugOrder.doctorId = t.value());
                    f = $(r).find("#appoint").data("kendoDropDownList");
                    f && f.value() && (n.currentDrugOrder.appointId = f.value());
                    n.oldDrugOrder.doctorId = n.oldDrugOrder.doctorId ? n.oldDrugOrder.doctorId.toString() : n.oldDrugOrder.doctorId;
                    n.oldDrugOrder.appointId = n.oldDrugOrder.appointId ? n.oldDrugOrder.appointId.toString() : n.oldDrugOrder.appointId;
                    var c = angular.copy(n.currentDrugOrder),
                        l = angular.copy(n.oldDrugOrder),
                        i = angular.equals(c, l);
                    if (!i) return !0;
                    if (h = $(r).find("#drugOrderDetailGrid").data("kendoGrid"), h.saveChanges(), e = h.dataSource._data, e.length != n.oldDrugOrder.drugOrderDetailList.length) i = !1;
                    else
                        for (u = 0; u < n.oldDrugOrder.drugOrderDetailList.length; u++) {
                            if (o = n.oldDrugOrder.drugOrderDetailList[u], s = _.find(e, {
                                    did: o.did
                                }), o.did == -1 && (s = e[u]), !s) {
                                i = !1;
                                return
                            }
                            _.each(o, function(n, t) {
                                if (s[t] != n && typeof n != "object" && t != "id") {
                                    i = !1;
                                    return
                                }
                            })
                        }
                    return !i
                },
                c = function() {
                    var t, i;
                    n.isEdit = !1;
                    f(n.currentDrugOrder.drugOrderDetailList, !1);
                    t = r.find("#appoint").data("kendoDropDownList");
                    t && t.enable(!1);
                    i = r.find("#doctor").data("kendoNameCodeFilterComboBox");
                    i && i.enable(!1);
                    r.find("#remark").attr("disabled", "disabled");
                    r.find("#btnSave").attr("disabled", "disabled");
                    e()
                },
                f = function(t, i) {
                    var u = [{
                        field: "drugName",
                        title: "名称",
                        width: "130px"
                    }, {
                        field: "specifications",
                        title: "规格",
                        width: "130px"
                    }, {
                        field: "count",
                        title: "数量",
                        width: "100px"
                    }, {
                        field: "price",
                        title: "单价",
                        width: "100px"
                    }, {
                        field: "unit",
                        title: "单位",
                        width: "100px"
                    }, {
                        field: "usage",
                        title: "用法"
                    }, {
                        command: {
                            text: "删除",
                            click: n.deleteFromDurgOrder,
                            template: function() {
                                return n.isEdit ? '<input type="button" class="lc-btn lc-btn-default default-btn btn-delete-detail" value="删除" />' : '<input type="button" class="lc-btn lc-btn-default default-btn" value="删除" disabled="disabled"/>'
                            }
                        },
                        title: "操作",
                        width: "120px"
                    }];
                    $(r).find("#drugOrderDetailGrid").kendoGrid({
                        dataSource: {
                            data: t,
                            schema: {
                                model: {
                                    id: "id",
                                    fields: {
                                        drugName: {
                                            type: "string",
                                            editable: !1
                                        },
                                        specifications: {
                                            type: "string",
                                            editable: !1
                                        },
                                        unit: {
                                            type: "string",
                                            editable: !1
                                        },
                                        count: {
                                            type: "number",
                                            validation: {
                                                required: !0,
                                                min: 1
                                            },
                                            editable: i
                                        },
                                        usage: {
                                            type: "string",
                                            editable: i
                                        }
                                    }
                                }
                            }
                        },
                        editable: i,
                        save: function(t) {
                            for (var i in t.values)
                                if (t.values.hasOwnProperty(i)) {
                                    let r = n.currentDrugOrder.drugOrderDetailList.find(n => n.id === t.model.id);
                                    r && (r[i] = t.values[i])
                                }
                        },
                        height: 220,
                        scrollable: !0,
                        selectable: "cell",
                        sortable: {
                            mode: "single",
                            allowUnsort: !1
                        },
                        columns: u,
                        dataBound: function() {
                            var t = this;
                            r.find(".btn-delete-detail").click(function(i) {
                                n.deleteFromDurgOrder.call(t, i)
                            })
                        }
                    })
                },
                l = function() {
                    r.find("#doctor").kendoNameCodeFilterComboBox({
                        dataSource: n.doctors,
                        filter: "contains",
                        placeholder: "请选择医生",
                        dataTextField: "name",
                        dataValueField: "id",
                        select: function(t) {
                            var i = this.dataItem(t.item.index());
                            n.currentDrugOrder.doctorName = i.name;
                            n.currentDrugOrder.doctorId = i.id;
                            n.drugDoctor = i
                        }
                    })
                },
                a = function(n) {
                    var t = r.find("#doctor").data("kendoNameCodeFilterComboBox");
                    t.value(n)
                },
                v = function() {
                    r.find("#appoint").kendoDropDownList({
                        dataSource: n.historyAppts,
                        placeholder: "请选择",
                        valueTemplate: '<span class="k-state-default">#: data.startTime #<\/span>',
                        template: '<span class="k-state-default">#: data.startTime #<\/span>',
                        dataValueField: "id",
                        select: function(t) {
                            var i = this.dataItem(t.item.index());
                            n.currentDrugOrder.appointTime = i.startTime;
                            n.currentDrugOrder.appointId = i.id;
                            n.drugOrderAppt = i;
                            n.initDrugOrderByYibaoOrder(i.id)
                        }
                    })
                },
                o = null,
                s = function() {
                    o = r.find("#feeType").kendoDropDownList({
                        dataSource: ["自费", "医保"],
                        select: function(t) {
                            var i = this.dataItem(t.item.index());
                            n.currentDrugOrder.feeType = i
                        }
                    })
                },
                y = function(n) {
                    o || s();
                    var t = r.find("#feeType").data("kendoDropDownList");
                    n = n && n.length > 0 ? n : "自费";
                    t.value(n)
                };
            (function() {
                n.element = r;
                n.isDrugOrderChanged = !1;
                n.getDrugOrderIsChange = h;
                n.disableEdit = c;
                n.initDetailGrid = f;
                n.initDoctorDropdownlist = l;
                n.setDoctor = a;
                s();
                v();
                n.setFeeType = y
            })()
        }
    }
}]);
patientModule.directive("patientDrugorderTableView", ["$log", "$timeout", "$window", function(n, t, i) {
    "use strict";
    return {
        templateUrl: "/app/patient/views/patient-drugorder-table-view.html",
        controller: "PatientDrugOrderCtrl",
        link: function(n, t) {
            var e = Ares.kendoGridUtil(i, n),
                r = !1,
                o = function() {
                    var t = [{
                        field: "index",
                        title: "编号",
                        width: "50px"
                    }, ];
                    return n.isInternWorkflowEnabled && n.drugOrderWorkflow && t.push({
                        field: "index",
                        title: "审批状态",
                        width: "80px",
                        template: function(n) {
                            return n.workflowStatus == 1 ? '<span class="work-flow-in-progress">待审批<\/span>' : n.workflowStatus == 2 ? '<span class="work-flow-approved">审批通过<\/span>' : n.workflowStatus == 3 ? '<span class="work-flow-rejected">审批拒绝<\/span>' : ""
                        }
                    }), n.$root.isRegularChain && t.push({
                        field: "officeName",
                        title: "诊所",
                        width: "60px"
                    }), t.push({
                        field: "orderDataTime",
                        title: "处方时间",
                        width: "50px"
                    }, {
                        field: "apptTime",
                        title: "就诊时间",
                        width: "50px"
                    }, {
                        field: "doctorName",
                        title: "处方医生",
                        width: "60px"
                    }, {
                        field: "comments",
                        title: "备注",
                        width: "120px"
                    }, {
                        template: e.commandTemplate,
                        title: "",
                        width: "50px"
                    }), t
                },
                u = function() {
                    if (n.data.drugOrders) {
                        r = !0;
                        var i = t.find("#drugorderList");
                        i.kendoGrid({
                            dataSource: {
                                data: n.data.drugOrders
                            },
                            scrollable: !1,
                            sortable: !0,
                            selectable: "single",
                            model: {
                                id: "id"
                            },
                            columns: o()
                        })
                    }
                },
                s = [{
                    text: "修改处方",
                    action: "goTodrug",
                    icon: "glyphicon-edit"
                }, ],
                f = function(t) {
                    return _.find(n.data.drugOrders, function(n) {
                        return n.id == t
                    })
                },
                h = function(t, i, r) {
                    n.$apply(function() {
                        var t = f(r);
                        switch (i) {
                            case "goTodrug":
                                n.editDrugOrder(t)
                        }
                    })
                },
                c = function() {
                    var t = $("#drugorderList"),
                        i = t.data("kendoGrid");
                    i.dataSource.data(n.data.drugOrders)
                };
            (function() {
                n.commands = s;
                n.onCommandClick = h;
                n.findPat = f;
                n.initData().then(function() {
                    u()
                });
                n.$watch("data.drugOrders", function() {
                    r ? c() : n.initData().then(function() {
                        u()
                    })
                })
            })()
        }
    }
}]);
patientModule.directive("patientDrugorderView", ["$log", "$timeout", "$modal", "$state", "appNav", "enums", "eventAggregator", function(n, t, i, r, u) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/views/patient-drugorder-view.html",
        controller: "PatientDrugOrderCtrl",
        scope: {
            patientId: "="
        },
        link: function(n) {
            var t = function(n) {
                    u.switchState(n, i)
                },
                i = function() {
                    var t = n.patientId;
                    return {
                        patientId: t
                    }
                };
            (function() {
                n.switchState = t
            })()
        }
    }
}]);
patientModule.directive("patientEditView", ["$log", "$timeout", "$modal", "enums", "practiceSvc", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "PatientRecordCtrl",
        templateUrl: "/app/patient/views/patient-edit-view.html",
        scope: {
            patientId: "=",
            add: "&",
            send: "&",
            start: "&",
            stop: "&",
            fail: "&",
            destroy: "&",
            done: "&",
            uploadprogress: "&"
        },
        link: function(n, t) {
            var r = function() {
                    Ares.validateForm(t.find("#patientForm"), n.validateList, n.validateMessageList)
                },
                u = function() {
                    var r, i;
                    n.bodycheck.disease = t.find("#Disease").data("kendoAresMultiSelect").value().join(",");
                    n.bodycheck.medicine = t.find("#Medicine").data("kendoAresMultiSelect").value().join(",");
                    n.bodycheck.medicineNow = t.find("#MedicineNow").data("kendoAresMultiSelect").value().join(",");
                    f();
                    r = t.find("#attendantInput");
                    n.patient.attendantId = r ? t.find("#attendantInput").data("kendoDropDownList").value() : null;
                    i = t.find("#patientTag");
                    i && (n.patient.tag = i.data("kendoMultiSelect").value())
                },
                f = function() {
                    if (n.patient.sourceType != "朋友介绍" && n.patient.sourceType != "员工介绍" && n.patient.sourceType) {
                        var i = t.find("#otherSourceType").data("kendoAresSingleSelect");
                        i && (n.patient.refereeName = i.value().join(","))
                    }
                },
                e = function() {
                    n.validateList = {
                        patientName: "required",
                        birth: {
                            dateCn: !0,
                            dateMax: !0
                        },
                        mobile: {
                            mobile: !0
                        },
                        email: {
                            email: !0
                        },
                        weixin: {
                            maxlength: 20
                        },
                        qq: {
                            maxlength: 20
                        },
                        homeAddress: {
                            maxlength: 255
                        },
                        notes: {
                            maxlength: 2e3
                        },
                        identityCard: {
                            identityCard: !0
                        },
                        phoneNumber: {
                            maxlength: 20
                        },
                        otherPrivateId: {
                            maxlength: 20
                        },
                        firstVisitDate: {
                            dateCn: !0,
                            dateMax: !0
                        },
                        nation: {
                            maxlength: 40
                        },
                        bloodType: {
                            maxlength: 20
                        },
                        nativePlace: {
                            maxlength: 40
                        },
                        job: {
                            maxlength: 40
                        },
                        religion: {
                            maxlength: 40
                        },
                        passportNo: {
                            maxlength: 60
                        },
                        marriageRadios: {},
                        educationLevelRadios: {},
                        sourceType: {},
                        age: {},
                        tags: {},
                        onlineConsultantId: {},
                        idCardIssuer: {},
                        idCardValidTo: {}
                    };
                    n.validateMessageList = {
                        patientName: "请输入姓名",
                        birth: {
                            dateCn: "请输入合法的日期",
                            dateMax: "生日不能大于当前时间！"
                        },
                        mobile: {
                            mobile: "请输入正确的手机号码!"
                        },
                        email: {
                            email: "请输入正确的邮箱"
                        },
                        weixin: {
                            maxlength: "长度最多为20个字符!"
                        },
                        qq: {
                            maxlength: "长度最多为20个字符!"
                        },
                        homeAddress: {
                            maxlength: "长度最多为255个字符!"
                        },
                        notes: {
                            maxlength: "长度最多为2000个字符!"
                        },
                        identityCard: {
                            identityCard: "请输入正确的身份证号码!"
                        },
                        phoneNumber: {
                            maxlength: "长度最多为20个字符!"
                        },
                        otherPrivateId: {
                            maxlength: "长度最多为20个字符!"
                        },
                        firstVisitDate: {
                            dateCn: "请输入合法的日期",
                            dateMax: "初诊日期不能大于当前时间！"
                        },
                        nation: {
                            maxlength: "长度最多为40个字符!",
                            required: "请输入民族"
                        },
                        bloodType: {
                            maxlength: "长度最多为40个字符!",
                            required: "请输入血型"
                        },
                        nativePlace: {
                            maxlength: "长度最多为40个字符!",
                            required: "请输入籍贯"
                        },
                        job: {
                            maxlength: "长度最多为40个字符!",
                            required: "请输入职业"
                        },
                        religion: {
                            maxlength: "长度最多为40个字符!",
                            required: "请输入宗教信仰"
                        },
                        passportNo: {
                            maxlength: "长度最多为60个字符!",
                            required: "请输入其他证件号"
                        },
                        marriageRadios: {
                            required: "请设置婚姻状况"
                        },
                        educationLevelRadios: {
                            required: "请设置文化程度"
                        },
                        sourceType: {},
                        age: {},
                        tags: {},
                        onlineConsultantId: {},
                        idCardIssuer: {},
                        idCardValidTo: {}
                    }
                },
                i = function() {
                    n.getPatientInfoFieldsConfig().then(function(t) {
                        e();
                        n.configFields = t;
                        var i = "isRequired";
                        i = patientType != "临时" ? "isRequired" : "isTempPatientRequired";
                        angular.forEach(t, function(t) {
                            typeof t.isTempPatientRequired == "undefined" && (t.isTempPatientRequired = t.isRequired);
                            t.name == "birthDay" && t[i] && t.isEnabled ? (n.validateList.birth.required = !0, n.validateMessageList.birth.required = "生日不能为空！") : t.name == "sex" && t[i] && t.isEnabled ? (n.validateList.sexRadios.required = !0, n.validateMessageList.sexRadios.required = "性别必须设置！") : t.name == "mobile" && t[i] && t.isEnabled ? (n.validateList.mobile.required = !0, n.validateMessageList.mobile.required = "手机不能为空！") : t.name == "phoneNumber" && t[i] && t.isEnabled ? (n.validateList.phoneNumber.required = !0, n.validateMessageList.phoneNumber.required = "电话不能为空！") : t.name == "firstVisit" && t[i] && t.isEnabled ? (n.validateList.firstVisitDate.required = !0, n.validateMessageList.firstVisitDate.required = "初诊时间不能为空！") : t.name == "notes" && t[i] && t.isEnabled ? (n.validateList.notes.required = !0, n.validateMessageList.notes.required = "患者备注不能为空！") : t.name == "sourceType" && t[i] && t.isEnabled ? (n.validateList.sourceType.required = !0, n.validateMessageList.sourceType.required = "患者来源不能为空！") : t.name == "identityCard" && t[i] && t.isEnabled ? (n.validateList.identityCard.required = !0, n.validateMessageList.identityCard.required = "身份证不能为空！") : t.name == "email" && t[i] && t.isEnabled ? (n.validateList.email.required = !0, n.validateMessageList.email.required = "邮箱不能为空！") : t.name == "qq" && t[i] && t.isEnabled ? (n.validateList.qq.required = !0, n.validateMessageList.qq.required = "QQ不能为空！") : t.name == "weixin" && t[i] && t.isEnabled ? (n.validateList.weixin.required = !0, n.validateMessageList.weixin.required = "微信不能为空！") : t.name == "homeAddress" && t[i] && t.isEnabled ? (n.validateList.homeAddress.required = !0, n.validateMessageList.homeAddress.required = "地址不能为空！") : t.name == "age" && t[i] && t.isEnabled ? (n.validateList.age.required = !0, n.validateMessageList.age.required = "年龄不能为空！") : t.name == "tags" && t[i] && t.isEnabled ? (n.validateList.tags.required = !0, n.validateMessageList.tags.required = "标签不能为空！") : t.name == "nickName" && t[i] && t.isEnabled ? (n.validateList.nickName.required = !0, n.validateMessageList.nickName.required = "昵称不能为空！") : t.name == "nationality" && t[i] && t.isEnabled ? (n.validateList.nationality.required = !0, n.validateMessageList.nationality.required = "国籍不能为空！") : t.name == "doctorId" && t[i] && t.isEnabled ? (n.validateList.doctorId.required = !0, n.validateMessageList.doctorId.required = "初诊医生不能为空！") : t.name == "dutyDoctorId" && t[i] && t.isEnabled ? (n.validateList.dutyDoctorId.required = !0, n.validateMessageList.dutyDoctorId.required = "责任医生不能为空！") : t.name == "attendantId" && t[i] && t.isEnabled ? (n.validateList.attendantId.required = !0, n.validateMessageList.attendantId.required = "专属客服不能为空！") : t.name == "onlineConsultantId" && t[i] && t.isEnabled ? (n.validateList.onlineConsultantId.required = !0, n.validateMessageList.onlineConsultantId.required = "网电咨询师不能为空！") : t.name == "developerId" && t[i] && t.isEnabled ? (n.validateList.developerId.required = !0, n.validateMessageList.developerId.required = "开发人员不能为空！") : t.name == "nation" && t[i] && t.isEnabled ? (n.validateList.nation.required = !0, n.validateMessageList.nation.required = "民族不能为空！") : t.name == "bloodType" && t[i] && t.isEnabled ? (n.validateList.bloodType.required = !0, n.validateMessageList.bloodType.required = "血型不能为空！") : t.name == "nativePlace" && t[i] && t.isEnabled ? (n.validateList.nativePlace.required = !0, n.validateMessageList.nativePlace.required = "籍贯不能为空！") : t.name == "marriage" && t[i] && t.isEnabled ? (n.validateList.marriageRadios.required = !0, n.validateMessageList.marriageRadios.required = "婚姻状况必须设置！") : t.name == "job" && t[i] && t.isEnabled ? (n.validateList.job.required = !0, n.validateMessageList.job.required = "职业不能为空！") : t.name == "religion" && t[i] && t.isEnabled ? (n.validateList.religion.required = !0, n.validateMessageList.religion.required = "宗教信仰不能为空！") : t.name == "passportNo" && t[i] && t.isEnabled ? (n.validateList.passportNo.required = !0, n.validateMessageList.passportNo.required = "其他证件号不能为空！") : t.name == "educationLevel" && t[i] && t.isEnabled ? (n.validateList.educationLevelRadios.required = !0, n.validateMessageList.educationLevelRadios.required = "文化程度必须设置！") : t.name == "patientIcon" && t[i] && t.isEnabled ? (n.validateList.patientIcon.required = !0, n.validateMessageList.patientIcon.required = "患者头像必须上传！") : t.name == "consultantId" && t[i] && t.isEnabled ? (n.validateList.consultantId.required = !0, n.validateMessageList.consultantId.required = "咨询师不能为空！") : t.name == "medicine" && t[i] && t.isEnabled ? (n.validateList.medicine.required = !0, n.validateMessageList.medicine.required = "过敏史不能为空！") : t.name == "disease" && t[i] && t.isEnabled ? (n.validateList.disease.required = !0, n.validateMessageList.disease.required = "既往史不能为空！") : t.name == "medicineNow" && t[i] && t.isEnabled ? (n.validateList.medicineNow.required = !0, n.validateMessageList.medicineNow.required = "用药史不能为空！") : t.name == "idCardIssuer" && t[i] && t.isEnabled ? (n.validateList.idCardIssuer.required = !0, n.validateMessageList.idCardIssuer.required = "发证机关不能为空！") : t.name == "idCardValidTo" && t[i] && t.isEnabled && (n.validateList.idCardValidTo.required = !0, n.validateMessageList.idCardValidTo.required = "有效期不能为空！")
                        });
                        r()
                    })
                },
                o = function() {
                    if (u(), n.validateList.sourceType.required && n.patient.sourceType == null) {
                        n.showErrorNotification("患者来源不能为空！");
                        return
                    }
                    if (n.validateList.tags.required && (!n.patient.tag || n.patient.tag == "")) {
                        n.showErrorNotification("请配置患者标签！");
                        return
                    }
                    t.find("#patientForm").valid() && (n.patient.birth = t.find("#birth").val(), n.save())
                };
            (function() {
                n.action = "edit";
                n.ok = o;
                i();
                n.getOfficeSetting = i
            })()
        }
    }
}]);
patientModule.directive("patientFollowupTableView", ["$log", "$timeout", "$window", "$modal", "$filter", "officeOptionSvc", "permissionProvider", "patientUtil", "patientTabManager", "appNav", "aresDialog", "enums", "followupUtil", "followupSvc", "loginContext", "patientSvc", "eventAggregator", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v, y, p, w) {
    "use strict";
    return {
        templateUrl: "/app/patient/views/patient-followup-table-view.html",
        controller: "PatientFollowupCtrl",
        link: function(n, h) {
            var g, nt = function(n) {
                    var t = u("toOfficeAbbr");
                    return n.officeId ? t(n.officeId) : ""
                },
                tt = function(n) {
                    return n.followupRule ? n.followupRule.ruleName : ""
                },
                it = function(n) {
                    var t = "<span>" + n.visitDateTime + "<br />" + (n.followupRuleAction ? "计划" + n.followupRuleAction.showOrder : "") + "<\/span>";
                    return n.visitDateTime ? t : ""
                },
                rt = function() {
                    return n.consultantName
                },
                ut = function(n) {
                    var t = n.creatorName ? n.creatorName : "",
                        i = n.recordCreatedTime ? n.recordCreatedTime : "",
                        r = "<span>" + t + "<br />" + i + "<\/span>";
                    return n.visitDateTime ? r : ""
                },
                ft = function(n) {
                    var t = '<span title="' + n.visitContent + '" data-toggle="tooltip" data-placement="top" data-container=".patient-followup-list">' + n.visitContent + "<\/span>";
                    return n.visitContent ? t : ""
                },
                et = function(n) {
                    var t = '<span class="overflow-content" title="' + n.visitResult + '">' + n.visitResult + "<\/span>";
                    return n.visitResult ? t : ""
                },
                ot = function(n) {
                    var t = '<div style="color: ' + n.statusTextColor + '">' + n.status + '<span class="exceed-sign" style="display: ' + (n.visitTimeExceed ? "inline" : "none") + ' ">超时<\/span><\/div>';
                    return n.status ? t : ""
                },
                st = function(n) {
                    var t = n.executorName ? n.executorName : "",
                        i = n.executeTime ? n.executeTime : "";
                    return "<span>" + t + "<br />" + i + "<\/span>"
                },
                ht = function(t) {
                    var u = "",
                        i, r, f;
                    return t.status === "待计划" && (u = '<a class="action-btn" action="exec" type-id="' + t.id + '" title="执行随访" data-toggle="tooltip" data-placement="top" data-container=".patient-followup-list">执行<\/a>'), i = "", t.status !== "已取消" && (i = '<a class="action-btn" action="edit" type-id="' + t.id + '" title="修改随访" data-toggle="tooltip" data-placement="top" data-container=".patient-followup-list">修改<\/a>'), r = "", n.isDeleteFollowupAllowed && (r = '<a class="action-btn" action="delete" type-id="' + t.id + '" title="删除随访" data-toggle="tooltip" data-placement="top" data-container=".patient-followup-list">删除<\/a>'), f = '<a class="action-btn" action="editLog" type-id="' + t.id + '" title="改动日志" data-toggle="tooltip" data-placement="top" data-container=".patient-followup-list">日志<\/a>', u + i + r + f
                },
                ct = function() {
                    return [{
                        field: "_index",
                        title: "编号",
                        width: "50px"
                    }, {
                        field: "",
                        title: "诊所",
                        width: "120px",
                        template: nt,
                        hidden: !n.isRegularChain
                    }, {
                        field: "category",
                        title: "随访类型",
                        width: "130px",
                        hidden: !0
                    }, {
                        field: "",
                        title: "计划随访时间",
                        width: "130px",
                        template: it
                    }, {
                        field: "doctorName",
                        title: "随访医生",
                        width: "130px"
                    }, {
                        field: "otherProviderName",
                        title: "随访人员",
                        width: "100px"
                    }, {
                        field: "",
                        title: "随访内容",
                        width: "260px",
                        template: ft
                    }, {
                        field: "",
                        title: "随访结果",
                        width: "260px",
                        template: et
                    }, {
                        field: "executorName",
                        title: "随访人/随访时间",
                        width: "130px",
                        template: st
                    }, {
                        field: "examDateTime",
                        title: "就诊时间",
                        width: "130px"
                    }, {
                        field: "",
                        title: "随访模板",
                        width: "130px",
                        template: tt,
                        hidden: !0
                    }, {
                        field: "subject",
                        title: "随访项目",
                        width: "130px",
                        hidden: !0
                    }, {
                        field: "",
                        title: "咨询师",
                        width: "100px",
                        template: rt,
                        hidden: !(n.isRegularChain && n.isEnableConsultantDiagnose)
                    }, {
                        field: "creatorName",
                        title: "创建人/时间",
                        width: "130px",
                        template: ut
                    }, {
                        field: "channel",
                        title: "沟通方式",
                        width: "130px",
                        hidden: !0
                    }, {
                        field: "satisfaction",
                        title: "满意度",
                        width: "100px"
                    }, {
                        field: "",
                        title: "随访状态",
                        width: "120px",
                        locked: !0,
                        template: ot
                    }, {
                        field: "",
                        title: "操作",
                        width: "150px",
                        locked: !0,
                        template: ht
                    }]
                },
                lt = function() {
                    var t = h.find(".patient-followup-list"),
                        r, u;
                    t.html("");
                    r = t.offset().top;
                    u = i.innerHeight - r - 50;
                    g = t.kendoGrid({
                        dataSource: {
                            data: n.followups
                        },
                        height: u,
                        model: {
                            id: "id"
                        },
                        columns: ct(),
                        dataBound: function() {}
                    }).data("kendoGrid")
                },
                at = function() {
                    h.find(".patient-followup-list").on("click", "a.action-btn", function() {
                        var i = $(this),
                            r = i.attr("type-id"),
                            u = i.attr("action"),
                            t = _.find(n.followups, function(n) {
                                return n.id === Number(r)
                            });
                        switch (u) {
                            case "exec":
                                wt(t).then(function() {
                                    b()
                                });
                                break;
                            case "edit":
                                pt(t).then(function() {
                                    b()
                                });
                                break;
                            case "delete":
                                yt(t).then(function() {
                                    b()
                                });
                                break;
                            case "editLog":
                                bt(t.id);
                                break;
                            default:
                                return
                        }
                    })
                },
                b = function() {
                    lt();
                    t(function() {
                        h.find("[data-toggle=tooltip]").tooltip()
                    })
                },
                k = function() {
                    n.getPatientFollowups().then(function(t) {
                        t = _.sortBy(t, "visitDateTime").reverse();
                        t.forEach(function(n, t) {
                            n.examDateTime = n.examDateTime ? moment(n.examDateTime).format("YYYY/MM/DD") : "";
                            n.visitDateTime = n.visitDateTime ? moment(n.visitDateTime).format("YYYY/MM/DD") : "";
                            n.recordCreatedTime = moment(n.recordCreatedTime).format("YYYY/MM/DD");
                            n.executeTime = n.executeTime ? moment(n.executeTime).format("YYYY/MM/DD") : "";
                            n._index = t + 1;
                            n.status === "待计划" ? (n.statusTextColor = "#F7A51D", n.visitTimeExceed = moment(n.visitDateTime) < moment(Ares.today())) : n.status === "随访完成" ? n.statusTextColor = "#00A6C9" : n.status === "已取消" && (n.statusTextColor = "#9397A2")
                        });
                        n.followups = t;
                        b()
                    })
                },
                vt = function() {
                    var i = u("toConsultantName"),
                        t;
                    n.isRegularChain = n.$root.isRegularChain;
                    t = s.activeTab.patient.consultantId;
                    n.consultantName = i(t);
                    k();
                    f.getOfficeOption(f.optionKeys.EnableConsultantDiagnose).then(function(t) {
                        n.isEnableConsultantDiagnose = t
                    });
                    n.isDeleteFollowupAllowed = e.isDeleteFollowupAllowed
                },
                yt = function(n) {
                    return o.checkFollowupPrivilege(n, "delete").then(function() {
                        c.confirm("删除随访记录", "确定要删除此随访记录？").then(function() {
                            v.deleteFollowup(n.id).success(function() {
                                k()
                            }).error(function(n) {
                                alert(n.data)
                            })
                        })
                    })
                },
                pt = function(t) {
                    if (t.officeId !== y.officeId) {
                        c.warn("信息", "不可修改其他诊所的随访记录。");
                        return
                    }
                    return o.checkFollowupPrivilege(t, "edit").then(function() {
                        p.getFollowup(t.id).success(function(t) {
                            n.handleType = "edit";
                            d(t)
                        })
                    })
                },
                wt = function(n) {
                    if (n.officeId !== y.officeId) {
                        c.warn("信息", "不可执行其他诊所的随访记录。");
                        return
                    }
                    return o.checkFollowupPrivilege(n, "view").then(function() {
                        var t = s.activeTab.patient;
                        p.getFollowup(n.id).success(function(n) {
                            n && (n.status = "随访完成");
                            a.openExecuteFollowupDialog(n, t).then(function(n) {
                                n && (k(), Ares.sensors.track("PatientFollowup", {
                                    OperationType: "执行随访"
                                }))
                            })
                        })
                    })
                },
                bt = function(n) {
                    var t = r.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<operation-log-list-view><\/operation-log-list-view>",
                        controller: "OperationLogListCtrl",
                        size: "lg",
                        windowClass: "operation-log-dialog",
                        resolve: {
                            host: function() {
                                return {
                                    id: n,
                                    type: "Followup"
                                }
                            }
                        }
                    })
                },
                kt = function() {
                    o.createFollowUpApptByPatientId(n.patientId).then(function(n) {
                        aresNotification.success("预约成功");
                        w.publish(w.events.AppointmentCreated, n, "patientFollowupView")
                    })
                },
                dt = function() {
                    var n = {
                        creatorId: y.userId,
                        followupRule: {
                            ruleType: l.FollowupRuleType.ManualRule,
                            creationMode: l.FollowupCreationMode.AllAtOnce,
                            timeMode: l.FollowupTimeMode.Absolute
                        },
                        appts: []
                    };
                    d(n)
                },
                d = function(t) {
                    var i = s.activeTab.patient;
                    t.pid = i.id;
                    a.openEditFollowupDialog(t, i).then(function(t) {
                        t && (k(), n.handleType && n.handleType == "edit" && Ares.sensors.track("PatientFollowup", {
                            OperationType: "修改随访"
                        }))
                    })
                };
            (function() {
                n.createFollowUpAppt = kt;
                n.onAddFollowup = dt;
                n.listHeight = {
                    height: angular.element(window).height() - 278
                };
                window.Ares3 && w.subscribe(n, w.events.sidebarSubMenuToggle, function() {
                    t(function() {
                        b()
                    })
                });
                vt();
                at()
            })()
        }
    }
}]);
patientModule.directive("patientFollowupView", ["$log", "$timeout", "$modal", "enums", "appNav", "aresNotification", "eventAggregator", "patientUtil", "followupUtil", "patientTabManager", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/views/patient-followup-view.html",
        controller: "PatientFollowupCtrl",
        scope: {
            patientId: "@"
        },
        link: function() {
            (function() {})()
        }
    }
}]);
patientModule.directive("patientHealthInsuranceView", ["$q", "$timeout", "$modal", "$state", "healthInsuranceSvc", "patientSvc", "aresNotification", function(n, t, i, r, u, f) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/views/patient-health-insurance-view.html",
        scope: {
            patientId: "="
        },
        link: function(t, i) {
            var e = function() {
                    var i = n.defer();
                    return f.getLitePatient(t.patientId).then(function(n) {
                        var t = n.data;
                        i.resolve(t)
                    }), i.promise
                },
                o = function() {
                    var t = n.defer();
                    return u.getServiceConfig().then(function(n) {
                        var i = n.data;
                        t.resolve(i)
                    }), t.promise
                },
                s = function() {
                    var i = e(),
                        u = o();
                    n.all([i, u]).then(function(n) {
                        return t.patient = n[0], t.config = n[1], h()
                    }).then(function() {
                        var n = "",
                            i;
                        t.patient.mData && (n = t.patient.mData["identityCardEncrypted"]);
                        n != "" ? f.decodeData(encodeURIComponent(n)).success(function(n) {
                            var i = {
                                containerId: "healthInsuranceList",
                                processId: null,
                                apiServer: t.config.baseUrl,
                                url: "/insurance/front/insurance-information",
                                token: t.config.accessToken,
                                params: JSON.stringify({
                                    patientId: t.patient.id,
                                    patientName: t.patient.name,
                                    identityType: "1",
                                    identityNumber: n,
                                    otherIdentityType: t.patient.passportType,
                                    otherIdentityNumber: t.patient.passportNo
                                })
                            };
                            InSurance(i);
                            r()
                        }) : (i = {
                            containerId: "healthInsuranceList",
                            processId: null,
                            apiServer: t.config.baseUrl,
                            url: "/insurance/front/insurance-information",
                            token: t.config.accessToken,
                            params: JSON.stringify({
                                patientId: t.patient.id,
                                patientName: t.patient.name,
                                identityType: "1",
                                identityNumber: t.patient.identityCard,
                                otherIdentityType: t.patient.passportType,
                                otherIdentityNumber: t.patient.passportNo
                            })
                        }, InSurance(i), r())
                    })
                },
                h = function() {
                    var i = n.defer();
                    return Ares.Loader.loadJs(t.config.baseUrl + "/plugin.js", function() {
                        i.resolve()
                    }), i.promise
                },
                r = function() {
                    var n = i.find("#healthInsuranceList iframe"),
                        t;
                    n && (t = $(window).height() - 175, n.height(t))
                };
            (function() {
                s()
            })()
        }
    }
}]);
patientModule.directive("patientHomeView", ["$log", "$timeout", "$modal", "$state", "appNav", "enums", "apptUtil", "aresDialog", "patientUtil", "patientSvc", "aresNotification", "eventAggregator", "loginContext", "$rootScope", function(n, t, i, r, u, f, e, o, s, h, c, l, a, v) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/views/patient-home-view.html",
        controller: ["$scope", function() {
            (function() {})()
        }],
        scope: {
            patientId: "="
        },
        link: function(n) {
            var t = function(t) {
                    a.isAdminOffice ? s.createAdminPatient(!0, n.patient) : u.switchState(t, r)
                },
                r = function() {
                    var t = n.patientId;
                    return {
                        patientId: t
                    }
                },
                f = function() {
                    s.createFollowUpApptByPatientId(n.patientId).then(function(n) {
                        n && c.success("预约成功")
                    })
                },
                o = function() {
                    s.createCrossOfficeFollowUpAppt(n.patientId).then(function(n) {
                        n && c.success("预约成功")
                    })
                },
                y = function() {
                    s.deletePatient(n.patient, !1, "patientHomeView").then(function() {
                        u.reload()
                    })
                },
                p = function() {
                    s.undoArchive(n.patient).then(function(t) {
                        n.patient = t;
                        u.reload()
                    })
                },
                w = function() {
                    h.getPatient(n.patientId).then(function(t) {
                        n.patient = t.data
                    })
                },
                b = function() {
                    if (v.isNewWxEnabled) {
                        var t = n.patient.marketCenterAccount;
                        v.$broadcast("start-chat", t)
                    } else l.publish(l.events.StartPaitnetConversation, n.patient, "patientRecordView")
                },
                k = function(n) {
                    var t = i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<operation-log-list-view><\/operation-log-list-view>",
                        controller: "OperationLogListCtrl",
                        size: "lg",
                        windowClass: "operation-log-dialog",
                        resolve: {
                            host: function() {
                                return {
                                    id: n,
                                    type: "Patient"
                                }
                            }
                        }
                    })
                };
            (function() {
                n.switchState = t;
                n.createFollowUpAppt = f;
                n.createCrossOfficeAppt = o;
                n.deletePatient = y;
                n.undoArchive = p;
                n.patientConversation = b;
                n.allowCrossOfficeAppt = e.allowCrossOfficeAppt();
                n.isOnlyShowCrossOfficeAppt = a.isAdminOffice;
                n.showPatientChangeLog = k;
                w();
                n.$on("bind-weixin", function(t, i) {
                    n.patient.marketCenterAccount = i
                })
            })()
        }
    }
}]);
patientModule.directive("patientInfoRecordView", ["$log", "$timeout", "$interval", "$q", "$window", "$modal", "dataDicSvc", "appNav", "patientSvc", "patientUtil", "loginContext", function(n, t, i, r, u, f, e, o, s, h, c) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "PatientInfoRecordCtrl",
        templateUrl: "/app/patient/views/patient-info-record-view.html",
        scope: {
            patientId: "="
        },
        link: function(n, i) {
            var u = {
                    infoBase: [],
                    infoFirstVisit: [],
                    infoExamination: [],
                    infoClientRelation: [],
                    infoPatientExtraSource: []
                },
                e = {
                    infoBase: [],
                    infoFirstVisit: [],
                    infoExamination: [],
                    infoClientRelation: [],
                    infoPatientExtraSource: []
                },
                l = function(n) {
                    return n && n.then && angular.isFunction(n.then)
                },
                a = function(n, t, i) {
                    u[n].push(t);
                    _.isFunction(i) && e[n].push(i)
                },
                o = function(n, t) {
                    var i = n[t].map(function(n) {
                        var i = n(),
                            t;
                        return l(i) ? i : (t = r.defer(), t.resolve(), t.promise)
                    });
                    return r.all(i)
                },
                v = function() {
                    n.infoBase = {};
                    n.infoBase.isEdit = !1;
                    n.infoClientRelation = {};
                    n.infoClientRelation.isEdit = !1;
                    n.infoExamination = {};
                    n.infoExamination.isEdit = !1;
                    n.infoFirstVisit = {};
                    n.infoFirstVisit.isEdit = !1;
                    n.infoPatientExtraSource = {};
                    n.infoPatientExtraSource.isEdit = !1
                },
                y = function(t) {
                    Ares.ensureNotDuplicated("onBlockEditing", 2e3) && n.initPatient().then(function() {
                        n.initVerifyPatientFieldInfo().then(function() {
                            n.infoBase.isEdit = !1;
                            n.infoClientRelation.isEdit = !1;
                            n.infoExamination.isEdit = !1;
                            n.infoFirstVisit.isEdit = !1;
                            n.infoPatientExtraSource.isEdit = !1;
                            n[t].isEdit = !0;
                            o(u, t)
                        })
                    })
                },
                p = function(t) {
                    n[t].isEdit = !1;
                    o(e, t)
                },
                w = function(t) {
                    return _.find(n.PatientInfoConfigFields, {
                        name: t
                    })
                },
                b = function(t, i) {
                    if (!n.verifyPatientFieldInfoDict) return !1;
                    var r = n.verifyPatientFieldInfoDict[t];
                    return n[i].isEdit && r && r.isEnabled ? n.patient.patientType == "临时" ? r.isTempPatientRequired : r.isRequired : !1
                },
                k = function(n) {
                    var t = i.find("#" + n),
                        u = t.data("kendoDropDownList"),
                        r;
                    if (u) {
                        u.focus();
                        return
                    }
                    if (r = t.data("kendoNumericTextBox"), r) {
                        r.focus();
                        return
                    }
                    t.focus()
                },
                d = function() {
                    var t = f.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<operation-log-list-view><\/operation-log-list-view>",
                        controller: "OperationLogListCtrl",
                        size: "lg",
                        windowClass: "operation-log-dialog",
                        resolve: {
                            host: function() {
                                return {
                                    id: n.patient.id,
                                    type: "PatientContact"
                                }
                            }
                        }
                    })
                },
                g = function() {
                    n.isShowPatientContact = !0;
                    c.isGhost || s.addViewPatientLog(n.patient.id, n.patient.name)
                },
                nt = function() {
                    var n = i.find(".notes-value-item.btn-icon");
                    n.tooltip()
                },
                tt = function() {
                    var n = localStorage.getItem("groupSchedulerAction"),
                        t;
                    n && (n = JSON.parse(n), n.operation == "patientinfo" && (t = $(document).find("div.modal.in"), t.length > 0 && t.data("$scope") && t.data("$scope").$dismiss && t.data("$scope").$dismiss(), n.operation = "", localStorage.setItem("groupSchedulerAction", JSON.stringify(n))))
                };
            (function() {
                n.focusRequiredItem = k;
                n.viewPatientContactLog = d;
                n.showContactView = g;
                n.isEditRequiredField = b;
                n.onBlockEditing = y;
                n.getConfigField = w;
                n.onCleanBlockEditing = p;
                n.registerOnEditingCallBackMethod = a;
                h.canEditPatient(n.patientId).then(function(t) {
                    n.isViewPatientInfo = t
                });
                n.initPatient().then(function() {
                    t(function() {
                        nt();
                        s.addViewPatientDetailLog(n.patient.id, n.patient.name)
                    }, 100)
                });
                v();
                tt()
            })()
        }
    }
}]);
patientModule.directive("patientPrintHistoryView", ["$log", "$q", "$timeout", "dataDicSvc", function(n, t, i, r) {
    return {
        replace: !0,
        templateUrl: "/app/patient/views/patient-print-history-view.html",
        link: function(n, u) {
            var f = null,
                o = function() {
                    u.find("#chargeOrderList td input[type='checkbox']").each(function() {
                        var t = this;
                        $(t).unbind("click").bind("click", function() {
                            var t = parseInt($(this).attr("chargeorderid")),
                                i;
                            this.checked ? n.addChargeOrderIds.indexOf(t) == -1 && n.addChargeOrderIds.push(t) : (i = n.addChargeOrderIds.indexOf(t), i > -1 && n.addChargeOrderIds.splice(i, 1))
                        })
                    });
                    u.find("#chargeOrderList th input[type='checkbox']").each(function() {
                        var n = this,
                            t;
                        $(n).attr("title", "全选");
                        $(n).attr("checked", !1);
                        t = $(n).attr("name");
                        t == "selectAll" && $(n).unbind("click").bind("click", function() {
                            this.checked ? e(!0) : e(!1)
                        })
                    })
                },
                e = function(t) {
                    n.addChargeOrderIds = [];
                    u.find("#chargeOrderList td input[type='checkbox']").each(function() {
                        var i = parseInt($(this).attr("chargeorderid"));
                        this.checked = t;
                        t && this.checked && n.addChargeOrderIds.indexOf(i) == -1 && n.addChargeOrderIds.push(i)
                    })
                },
                s = function() {
                    var i = t.defer(),
                        r = [{
                            title: "<div style='text-align: center;'><input name='selectAll' id='selectAll' type='checkbox' /><\/div>",
                            width: "40px",
                            template: "<input  type='checkbox' chargeorderid='#: id #'/>"
                        }, {
                            hidden: !n.$root.isRegularChain,
                            field: "officeName",
                            title: "操作诊所",
                            width: "130px",
                            headerAttributes: {
                                style: "text-align: center; font-size: 14px; font-weight: bolder;"
                            }
                        }, {
                            field: "payDateTime",
                            title: "首次收款时间",
                            width: "160px",
                            headerAttributes: {
                                style: "text-align: center; font-size: 14px; font-weight: bolder;"
                            }
                        }, {
                            field: "status",
                            title: "收费状态",
                            width: "50px",
                            headerAttributes: {
                                style: "text-align: center; font-size: 14px; font-weight: bolder;"
                            }
                        }, {
                            field: "visitTime",
                            title: "就诊时间",
                            width: "120px",
                            headerAttributes: {
                                style: "text-align: center; font-size: 14px; font-weight: bolder;"
                            }
                        }, {
                            hidden: n.isCDTmode,
                            field: "doctorName",
                            title: "医生",
                            width: "60px",
                            headerAttributes: {
                                style: "text-align: center; font-size: 14px; font-weight: bolder;"
                            }
                        }, {
                            hidden: n.isCDTmode,
                            field: "finalPrice",
                            title: "应收",
                            width: "40px",
                            format: "{0:n}",
                            headerAttributes: {
                                style: "text-align: center; font-size: 14px; font-weight: bolder;"
                            }
                        }, {
                            field: "actualPrice",
                            title: "实收",
                            width: "40px",
                            format: "{0:n}",
                            headerAttributes: {
                                style: "text-align: center; font-size: 14px; font-weight: bolder;"
                            }
                        }, {
                            hidden: n.isCDTmode,
                            field: "overdue",
                            title: "欠费",
                            format: "{0:n}",
                            width: "40px",
                            headerAttributes: {
                                style: "text-align: center; font-size: 14px; font-weight: bolder;"
                            }
                        }, ];
                    return i.resolve(r), i.promise
                },
                h = function() {
                    s().then(function(t) {
                        f = u.find("#chargeOrderList").kendoGrid({
                            dataSource: n.chargeorders,
                            scrollable: !0,
                            sortable: !0,
                            selectable: "single",
                            height: 400,
                            dataBound: o,
                            columns: t
                        }).data("kendoGrid")
                    })
                },
                c = function() {
                    f ? f.dataSource.data(n.chargeorders) : h()
                },
                v = function() {
                    var n = $(window).height() - 150;
                    $("#chargeOrderList").css("height", n)
                },
                l = function() {
                    var o = new Date,
                        i = angular.copy(n.addChargeOrderIds),
                        u = angular.copy(n.chargeOrder),
                        t = {},
                        f, e;
                    t.patientName = n.chargeOrder.patientName;
                    t.privateId = n.chargeOrder.privateId;
                    t.date = o;
                    t.finalPrice = 0;
                    t.actualPrice = 0;
                    t.overdue = 0;
                    t.chargeOrderHistory = [];
                    n.templateType === "A4HistoryTemplateDetail" && (f = _.filter(u.detailList, function(n) {
                        return _.contains(i, n.chargeOrdersId)
                    }), e = _.filter(u.totalPriceList, function(n) {
                        return _.contains(i, n.chargeOrdersId)
                    }), t.detailList = f, angular.element(e).each(function(n, i) {
                        t.finalPrice += i.finalPrice;
                        t.actualPrice += i.actualPrice;
                        t.overdue += i.overdue
                    }));
                    n.templateType === "A4HistoryTemplateRecord" && n.getChargeOrderHistoryInfoByIds(i).then(function(n) {
                        angular.element(n).each(function(n, i) {
                            angular.element(i.childChargeOrders).each(function(n, i) {
                                t.chargeOrderHistory.push(i)
                            })
                        });
                        angular.element(t.chargeOrderHistory).each(function(n, i) {
                            var u = r.officeDic.getItemSync(i.payOfficeId);
                            i.officeName = u.abbreviation ? u.abbreviation : u.name;
                            t.finalPrice += i.planPrice - i.discountPrice;
                            t.actualPrice += i.actualPrice;
                            t.overdue += i.overdue
                        })
                    });
                    n.selectedOrder = t
                },
                a = function(n) {
                    return Ares.priceToFixed(n)
                };
            (function() {
                n.$watch("chargeorders", function() {
                    n.chargeorders && (c(), n.addChargeOrderIds = [])
                });
                n.$watchCollection("addChargeOrderIds", function() {
                    n.addChargeOrderIds.length > 0 && l()
                });
                i(function() {
                    Ares.centerModal(u.closest(".modal-dialog"))
                }, 500);
                n.priceToFixed = a
            })()
        }
    }
}]);
patientModule.directive("patientRecordView", ["$log", "$timeout", "$interval", "$window", "$modal", "dataDicSvc", "appNav", "patientSvc", "loginContext", function(n, t, i, r, u, f, e, o, s) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "PatientRecordCtrl",
        templateUrl: "/app/patient/views/patient-record-view.html",
        scope: {
            patientId: "="
        },
        link: function(n, t) {
            r.PatientCtrl_goToPatient = function(n) {
                var i = t.find(n).closest("tr"),
                    r = t.find("#PatientRelation").data("kendoGrid"),
                    u = r.dataItem(i);
                return e.goToPatient(u.patientId), !1
            };
            f.medicineDic.load().then(function(t) {
                n.medicines = t
            });
            var l = function() {
                    var t = u.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<patient-referee-detail-view><\/patient-referee-detail-view>",
                        controller: "PatientRefereeDetailCtrl",
                        size: "lg",
                        resolve: {
                            host: function() {
                                return {
                                    patient: n.patient
                                }
                            }
                        }
                    })
                },
                a = function() {
                    n.patient.refereeId > 0 && o.getPatient(n.patient.refereeId).success(function(t) {
                        n.toPatient = t;
                        e.goToPatient(n.toPatient.id)
                    })
                },
                h = !0;
            n.initList = function() {
                if (n.patientRelation) {
                    var i = $(t).find("#PatientRelation");
                    h = !1;
                    i.kendoGrid({
                        dataSource: n.patientRelation,
                        scrollable: !1,
                        sortable: !0,
                        selectable: "single",
                        columns: [{
                            field: "relationType",
                            title: "关系",
                            width: "100px"
                        }, {
                            field: "patientName",
                            title: "关系人姓名",
                            width: "150px",
                            template: kendo.template($("#patientNameTemplate").html())
                        }, {
                            field: "sex",
                            title: "性别",
                            width: "100px"
                        }, {
                            field: "mobile",
                            title: "手机",
                            width: "100x"
                        }, {
                            field: "membershipType",
                            title: "会员卡类型",
                            width: "160px"
                        }, {
                            field: "cardNumber",
                            title: "会员卡账号",
                            width: "150px"
                        }, {
                            field: "relationMark",
                            title: "备注",
                            width: "100px"
                        }, ]
                    })
                }
            };
            var c = function() {
                    var i = null,
                        t, r;
                    if (!i)
                        for (t = n.$parent, r = 0; r < 10; r++)
                            if (t == null || t.patientTabManager) {
                                i = t;
                                break
                            } else t = t.$parent;
                    return i
                },
                v = function(n, t) {
                    o.updateAdvisor(n.id, t);
                    n.advisorId = t
                },
                y = function(n) {
                    o.undoAdvisor(n.id);
                    n.advisorId = null
                };
            (function() {
                n.showReferee = l;
                n.gotoPatient = a;
                n.findPatientTabManagerScope = c;
                n.cancelAdvisor = y;
                n.updateAdvisor = v;
                n.isGroup = s.isGroup;
                var t = i(function() {
                    var t = c();
                    t && t.patientTabManager.activeTab && t.patientTabManager.activeTab.patient && t.patientTabManager.activeTab.patient.marketCenterAccount && (n.patient.marketCenterAccount = t.patientTabManager.activeTab.patient.marketCenterAccount)
                }, 1e3);
                n.$watch("patientRelation", function() {
                    h && n.initList()
                });
                n.$on("$destroy", function() {
                    delete r.PatientCtrl_goToPatient;
                    t && i.cancel(t)
                })
            })()
        }
    }
}]);
patientModule.directive("patientRelationEditView", ["$log", "$timeout", "enums", "practiceSvc", function(n, t, i, r) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/views/patient-relation-edit-view.html",
        link: function(n, i) {
            var u = function() {
                r.getRelationType().success(function(t) {
                    if (t) {
                        var r = i.find("#relationType"),
                            u = r.kendoDropDownList({
                                dataSource: t,
                                dataTextField: "itemName",
                                dataValueField: "itemName",
                                value: n.relation.relationType,
                                select: function(t) {
                                    n.relation.relationType = this.dataItem(t.item)[this.options.dataValueField] || null
                                }
                            });
                        n.relation.relationType = t[0].itemName
                    }
                })
            };
            (function() {
                u()
            })();
            t(function() {
                Ares.centerModal(i.closest(".modal-dialog"))
            }, 100)
        }
    }
}]);
patientModule.directive("patientRevisitRecordView", ["loginContext", function(n) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "PatientRevisitRecordCtrl",
        templateUrl: "/app/patient/views/patient-revisit-record-view.html",
        scope: {
            patientId: "="
        },
        link: function(t, i) {
            var r = function(n) {
                    i.find(n.target).attr("class", "revisit-second-level-button-hover-class")
                },
                u = function(n) {
                    i.find(n.target).attr("class", "revisit-second-level-button-default-class")
                },
                f = function(n) {
                    i.find(n.target).attr("class", "revisit-third-level-button-hover-class")
                },
                e = function(n) {
                    i.find(n.target).attr("class", "revisit-third-level-button-default-class")
                };
            (function() {
                t.providerJob = n.providerJob;
                t.addMouseHoverClass = r;
                t.removeMouseHoverClass = u;
                t.addThirdLevelMouseHoverClass = f;
                t.removeThirdLevelMouseHoverClass = e
            })()
        }
    }
}]);
patientModule.directive("patientTxplanEditView", ["practiceSvc", "$timeout", "$window", function(n, t, i) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/views/patient-txplan-edit-view.html",
        link: function(n, r) {
            var f = null,
                e = function() {
                    var t = this;
                    $(r).find("#itemGrid table tbody tr").each(function(i, r) {
                        var u = t.dataItem(r),
                            f = _.find(n.giftPlanList, function(n) {
                                return n.itemName == u.itemName ? !0 : !1
                            });
                        f ? $("td.cell-command", r).find('button[data-action="add"]').remove() : $("td.cell-command", r).find('button[data-action="remove"]').remove()
                    })
                },
                o = function() {
                    var u = Ares.kendoGridUtil(i, n),
                        t;
                    n.chargeCatagoryList && (t = r.find("#itemGrid"), t.html(""), f = t.kendoGrid({
                        dataSource: {
                            data: n.chargeItemListFilteResult
                        },
                        height: 500,
                        sortable: !0,
                        selectable: "single",
                        dataBound: e,
                        columns: [{
                            field: "itemName",
                            title: "名称",
                            width: "150px",
                            attributes: {
                                "class": "cell-left"
                            }
                        }, {
                            field: "procedureCode",
                            title: "编码",
                            width: "80px",
                            attributes: {
                                "class": "cell-left"
                            }
                        }, {
                            field: "unit",
                            title: "单位",
                            width: "50px",
                            attributes: {
                                "class": "cell-left"
                            }
                        }, {
                            field: "price",
                            title: "单价",
                            width: "50px",
                            attributes: {
                                "class": "cell-left"
                            }
                        }, {
                            template: u.commandTemplate,
                            title: "",
                            width: "60px",
                            attributes: {
                                "class": "cell-command"
                            }
                        }]
                    }).data("kendoGrid"))
                },
                s = [{
                    text: "添加处置",
                    action: "add",
                    icon: "glyphicon-plus"
                }, {
                    text: "取消",
                    action: "remove",
                    icon: "glyphicon-minus"
                }],
                h = function(t) {
                    return _.find(n.chargeItemList, function(n) {
                        return n.id == t
                    })
                },
                c = function(t, i, r) {
                    n.$apply(function() {
                        var t = h(r),
                            u = {
                                id: t.id,
                                itemName: t.itemName,
                                itemId: t.id,
                                price: t.price,
                                count: 1
                            };
                        switch (i) {
                            case "add":
                                n.add(u);
                                break;
                            case "remove":
                                n.remove(u)
                        }
                    })
                },
                u = function() {
                    f ? n.chargeItemListFilteResult ? f.dataSource.data(n.chargeItemListFilteResult) : f.dataSource.data([]) : o()
                },
                l = function(t) {
                    var i = _.find(n.giftPlanList, function(n) {
                        return n.itemName == t.itemName ? !0 : !1
                    });
                    i ? alert("a") : (n.giftPlanList.push(t), u())
                },
                a = function(t) {
                    var i = _.findIndex(n.giftPlanList, function(n) {
                        return n.itemName == t.itemName ? !0 : !1
                    });
                    i > -1 && (n.giftPlanList.splice(i, 1), u())
                },
                v = function() {
                    n.chargeItemsFilter = "";
                    n.resetChargeItemList(null, n.defaultSupCategoryId)
                },
                y = function() {
                    n.chargeItemsFilter = "";
                    n.resetChargeItemList(n.defaultCategoryId)
                },
                p = function() {
                    n.chargeItemListFilteResult = n.chargeItemsFilter ? n.chargeItemList.filter(function(t) {
                        return t.itemName.indexOf(n.chargeItemsFilter) > -1 || t.pinyin && t.pinyin.indexOf(n.chargeItemsFilter) > -1
                    }) : angular.copy(n.chargeItemList);
                    u()
                };
            (function() {
                n.commands = s;
                n.onCommandClick = c;
                n.add = l;
                n.remove = a;
                n.onHandleTypeSelected = y;
                n.onHandleSupCategorySelect = v;
                n.chargeItemsFilter = "";
                n.filteChargeItemByFilter = p;
                n.$watch("chargeItemList", function() {
                    n.chargeItemListFilteResult = angular.copy(n.chargeItemList);
                    u()
                });
                n.$watch("selectHandleItem", function() {
                    n.selectHandleItem == !0 && (n.selectHandleCatagory = 0, n.chargeCatagoryList.length > 0 && (n.selectHandleCatagory = n.chargeCatagoryList[0].id, u()))
                })
            })();
            t(function() {
                Ares.centerModal(r.closest(".modal-dialog"))
            }, 5)
        }
    }
}]);
patientModule.directive("patientTxplanView", ["$log", "$timeout", "$window", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "PatientTxplanCtrl",
        templateUrl: "/app/patient/views/patient-txplan-view.html",
        scope: {
            patientId: "="
        },
        link: function() {
            (function() {})()
        }
    }
}]);
patientModule.directive("patientWeixinConsultView", ["$log", "$modal", "$timeout", "appointmentSvc", "practiceSvc", function(n, t, i) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/views/patient-weixin-consult-view.html",
        link: function(n, t) {
            (function() {})();
            i(function() {
                Ares.centerModal(t.closest(".modal-dialog"))
            }, 200)
        }
    }
}]);
patientModule.directive("patientDentalLabOrderView", ["$log", "$timeout", "$modal", "$window", "aresDialog", "enums", "eventAggregator", "aresModalShelf", "printUtil", "dentalLabSvc", "dataDicSvc", "loginContext", function(n, t, i, r, u, f, e, o, s, h, c, l) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/views/dental-lab/patient-dental-lab-order-view.html",
        controller: "PatientDentalLabOrderCtrl",
        scope: {
            patientId: "@"
        },
        link: function(n, e) {
            var w = function(t) {
                    var i = o.open({
                        title: "新建申请单",
                        titleIconClass: "iconfont icon-caigouoff",
                        template: "<ares3-patient-dental-lab-order-edit-modal-view><\/ares3-patient-dental-lab-order-edit-modal-view>",
                        controller: "Ares3PatientDentalLabOrderEditModalCtrl",
                        resolve: {
                            host: function() {
                                return {
                                    patientId: n.patientId,
                                    dentalLabOrderId: t
                                }
                            }
                        },
                        confirmClose: !0
                    });
                    i.result.then(function() {
                        n.searchDentalLabOrder()
                    })
                },
                p = function(t, i) {
                    var u = n.dentalLabOrder,
                        r = o.open({
                            title: "编辑申请单",
                            titleIconClass: "iconfont icon-caigouoff",
                            template: "<ares3-patient-dental-lab-order-edit-modal-view><\/ares3-patient-dental-lab-order-edit-modal-view>",
                            controller: "Ares3PatientDentalLabOrderEditModalCtrl",
                            resolve: {
                                host: function() {
                                    return {
                                        patientId: n.patientId,
                                        dentalLabOrderId: t,
                                        acceptanceResult: i
                                    }
                                }
                            },
                            confirmClose: !0
                        });
                    r.result.then(function() {
                        n.searchDentalLabOrder()
                    })
                },
                b = function(i) {
                    var r = o.open({
                        title: "技加工单详情",
                        titleIconClass: "iconfont icon-caigouoff",
                        template: "<ares3-patient-dental-lab-order-detail-modal-view><\/ares3-patient-dental-lab-order-detail-modal-view>",
                        controller: "Ares3PatientDentalLabOrderDetailModalCtrl",
                        resolve: {
                            host: function() {
                                return {
                                    dentalLabOrder: i
                                }
                            }
                        }
                    });
                    r.result.then(function(i) {
                        i && (n.searchDentalLabOrder(), i && i.furtherAction === "edit" && i.dentalLabOrderId && t(function() {
                            p(i.dentalLabOrderId)
                        }))
                    })
                },
                k = function() {
                    return i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<patient-dental-lab-order-acceptance-result-select-view><\/patient-dental-lab-order-acceptance-result-select-view>",
                        controller: "PatientDentalLabOrderAcceptanceResultSelectCtrl",
                        backdropClass: "ares-modal-backdrop",
                        resolve: {
                            dataHost: function() {
                                return {}
                            }
                        }
                    })
                },
                d = function(n) {
                    return i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<patient-dental-lab-order-difference-view><\/patient-dental-lab-order-difference-view>",
                        controller: "PatientDentalLabOrderDifferenceCtrl",
                        backdropClass: "ares-modal-backdrop",
                        resolve: {
                            dataHost: function() {
                                return {
                                    orderId: n
                                }
                            }
                        }
                    })
                },
                g = function() {
                    a();
                    var n = angular.element(r);
                    e.find(".table-main").mCustomScrollbar({
                        scrollButtons: {
                            enable: !1
                        },
                        autoHideScrollbar: !0,
                        scrollInertia: 150,
                        advanced: {
                            updateOnContentResize: !0
                        }
                    });
                    n.on("resize", function() {
                        a()
                    })
                },
                a = function() {
                    t(function() {
                        var t = angular.element(r).height(),
                            i = t - 300,
                            n = e.find(".table-main");
                        n.height(i);
                        n.mCustomScrollbar("update");
                        n.mCustomScrollbar("scrollTo", "top")
                    })
                },
                nt = function() {
                    n.searchDentalLabOrder().then(function() {
                        t(function() {
                            a()
                        })
                    })
                },
                v = function(n, t) {
                    return {
                        orderId: n,
                        action: f.DentalLabOrderAction[t]
                    }
                },
                y = function(t, i) {
                    u.confirm("提示", "确认要" + i + "该订单？").then(function() {
                        i == "提交" ? tt(t) : n.orderAction(t)
                    })
                },
                tt = function(t) {
                    var i = [t];
                    n.toSubmit(i)
                },
                it = function(n, t) {
                    y(n, t)
                },
                rt = function(n, t) {
                    var i = v(n, "Receive");
                    y(i, t)
                },
                ut = function(n, t) {
                    var i = v(n, "Mold");
                    y(i, t)
                },
                ft = function(t) {
                    var i = v(t, "Accept");
                    k().result.then(function(r) {
                        i.acceptanceResult = r;
                        n.orderAction(i).then(function() {
                            i.acceptanceResult > 1 && p(t, i.acceptanceResult)
                        })
                    })
                },
                et = function(n, t) {
                    var i = v(n, "Settle");
                    y(i, t)
                },
                ot = function(t) {
                    var i = t.orderStatus,
                        u = t.id,
                        r = n.operBtnNameObj;
                    switch (i) {
                        case 10:
                            it(t, r[i]);
                            break;
                        case 15:
                            ut(u, r[i]);
                            break;
                        case 20:
                            rt(u, r[i]);
                            break;
                        case 30:
                            ft(u, r[i]);
                            break;
                        case 40:
                            et(u, r[i])
                    }
                },
                st = function(n) {
                    d(n)
                },
                ht = function(i, r) {
                    h.getPrintDate(i).then(function(i) {
                        n.dentalLabOrderPrintDto = i.data;
                        var u = c.officeDic.getItemSync(l.officeId);
                        n.dentalLabOrderPrintDto.officeName = u.name;
                        t(function() {
                            r ? s.printElem("dentalLabOrderPrintLabelTemplate") : s.printElem("dentalLabOrderPrintTemplate")
                        })
                    })
                };
            (function() {
                n.createDentalLabOrder = w;
                n.viewDentalLabOrderDetail = b;
                n.initTableView = a;
                n.onSearchDentalLabOrder = nt;
                n.changeOrderStatus = ot;
                n.checkOrder = st;
                n.printOrder = ht;
                n.dentalLabOrderPrintDto = {};
                g()
            })()
        }
    }
}]);
patientModule.directive("patientDentalLabOrderAcceptanceResultSelectView", ["$window", "$log", "$timeout", "$q", function(n, t, i) {
    return {
        replace: !0,
        templateUrl: "/app/patient/views/dental-lab/dialogs/patient-dental-lab-order-acceptance-result-select/patient-dental-lab-order-acceptance-result-select-view.html",
        link: function(n, t) {
            var r = [{
                    name: "合格",
                    value: 1
                }, {
                    name: "返修",
                    value: 2
                }, {
                    name: "重做",
                    value: 3
                }],
                u = function() {
                    t.parents(".modal-dialog").css("width", "420px");
                    i(function() {
                        Ares.centerModal(t.closest(".modal-dialog"))
                    }, 50)
                },
                f = function() {
                    t.find("#result").kendoDropDownList({
                        dataSource: r,
                        optionLabel: "请选择验收结果",
                        dataTextField: "name",
                        dataValueField: "value",
                        change: function() {
                            n.result = this.value()
                        }
                    })
                },
                e = function() {
                    u();
                    f()
                };
            (function() {
                e()
            })()
        }
    }
}]);
patientModule.controller("PatientDentalLabOrderAcceptanceResultSelectCtrl", ["$log", "$scope", "$modalInstance", "aresNotification", function(n, t, i, r) {
    "use strict";
    var u = function() {
            i.dismiss()
        },
        f = function() {
            if (!t.result) {
                r.error("请选择验收结果！");
                return
            }
            i.close(t.result)
        };
    (function() {
        t.cancel = u;
        t.save = f
    })()
}]);
patientModule.directive("patientDentalLabOrderDetailView", ["$log", "$timeout", "$modal", "$window", "aresDialog", "enums", "eventAggregator", "aresModalShelf", function(n, t, i, r, u, f) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/views/dental-lab/dialogs/patient-dental-lab-order-detail/patient-dental-lab-order-detail-view.html",
        link: function(n) {
            var t = function() {
                    return i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<patient-dental-lab-order-remove-note-view><\/patient-dental-lab-order-remove-note-view>",
                        controller: "PatientDentalLabOrderRemoveNoteCtrl",
                        backdropClass: "ares-modal-backdrop",
                        resolve: {
                            dataHost: function() {
                                return {}
                            }
                        }
                    })
                },
                r = function(n, t) {
                    return i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<patient-dental-lab-order-logs-view><\/patient-dental-lab-order-logs-view>",
                        controller: "PatientDentalLabOrderLogsCtrl",
                        backdropClass: "ares-modal-backdrop",
                        resolve: {
                            dataHost: function() {
                                return {
                                    orderId: n,
                                    orderNo: t
                                }
                            }
                        }
                    })
                },
                u = function(n, t) {
                    return {
                        orderId: n,
                        action: f.DentalLabOrderAction[t]
                    }
                },
                e = function(i) {
                    var r = u(i, "Abort");
                    t().result.then(function(t) {
                        r.note = t;
                        n.orderAction(r)
                    })
                },
                o = function() {
                    n.$modalInstance.close({
                        furtherAction: "edit",
                        dentalLabOrderId: n.dentalLabOrder.id,
                        patientId: n.dentalLabOrder.patientId
                    })
                },
                s = function(n) {
                    i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<ares-picture-preview-dialog-view><\/ares-picture-preview-dialog-view>",
                        controller: "AresPicturePreviewDialogCtrl",
                        backdropClass: "ares-modal-backdrop",
                        resolve: {
                            host: function() {
                                return {
                                    picture: {
                                        pictureName: n.pictureName,
                                        filePath: n.filePath
                                    }
                                }
                            }
                        }
                    })
                };
            (function() {
                n.removeOrder = e;
                n.editOrder = o;
                n.logs = r;
                n.preViewPicture = s
            })()
        }
    }
}]);
patientModule.controller("PatientDentalLabOrderDetailCtrl", ["$log", "$scope", "$modalInstance", "$q", "constants", "loginContext", "dataHost", "dentalLabSvc", "appointmentSvc", function(n, t, i, r, u, f, e, o, s) {
    "use strict";
    var h = function() {
            var n = {
                officeId: f.officeId,
                patientId: t.dentalLabOrder.patientId,
                endTime: moment(Ares.today()).add(1, "d").format(u.dateFormat),
                isCancelled: !1,
                isPending: !1,
                isFailed: !1
            };
            s.searchAppointments(n).success(function(n) {
                var r, i;
                if (n.length > 0)
                    for (r = angular.copy(n), i = 0; i < n.length; ++i) t.dentalLabOrder.appointmentId == n[i].id && (t.appointmentTime = moment(n[i].startTime).format("YYYY年MM月DD日 HH:mm"))
            })
        },
        c = function() {
            o.getOrderById(t.dentalLabOrder.id).then(function(n) {
                t.pictures = n.data.pictures
            })
        },
        l = function(n) {
            o.orderAction(n).then(function(n) {
                t.$modalInstance.close(n)
            })
        },
        a = function() {
            h();
            c();
            v()
        },
        v = function() {
            t.dentalLabOrder && t.dentalLabOrder.dentalLabOrderDetailDtos && _.each(t.dentalLabOrder.dentalLabOrderDetailDtos, function(n) {
                n.toothCode && angular.isArray(n.toothCode) && (n.toothCodeStr = n.toothCode.join(","))
            })
        };
    (function() {
        t.dentalLabOrder = e.dentalLabOrder;
        t.orderAction = l;
        a()
    })()
}]);
patientModule.directive("patientDentalLabOrderDifferenceView", ["$window", "$log", "$timeout", "$q", function(n, t, i) {
    return {
        replace: !0,
        templateUrl: "/app/patient/views/dental-lab/dialogs/patient-dental-lab-order-difference/patient-dental-lab-order-difference-view.html",
        link: function(n, t) {
            var r = function() {
                t.parents(".modal-dialog").css("width", "760px");
                i(function() {
                    Ares.centerModal(t.closest(".modal-dialog"))
                }, 50)
            };
            (function() {
                r()
            })()
        }
    }
}]);
patientModule.controller("PatientDentalLabOrderDifferenceCtrl", ["$log", "$scope", "$modalInstance", "aresNotification", "dataHost", "dentalLabSvc", function(n, t, i, r, u, f) {
    "use strict";
    var e = function() {
            i.dismiss()
        },
        o = function() {
            f.orderDifference(t.orderId).then(function(n) {
                var i = n.data;
                s(i);
                t.orderData = i
            })
        },
        s = function(n) {
            var i = 0;
            _.each(n.details, function(n) {
                n.balance && (i += parseFloat(n.balance))
            });
            t.balance = parseFloat(i).toFixed(2)
        },
        h = function() {
            i.close()
        };
    (function() {
        t.cancel = e;
        t.save = h;
        t.orderId = u.orderId;
        o()
    })()
}]);
patientModule.directive("patientDentalLabOrderEditView", ["$window", "$log", "$timeout", "$q", "$modal", "loginContext", "enums", "aresDialog", "aresNotification", function(n, t, i, r, u, f, e, o, s) {
    return {
        replace: !0,
        templateUrl: "/app/patient/views/dental-lab/dialogs/patient-dental-lab-order-edit/patient-dental-lab-order-edit-view.html",
        link: function(n, t) {
            var i, r, a = function() {
                    var u = n.historyAppts,
                        i;
                    (!n.dentalLabOrderData.appointmentId || n.dentalLabOrderData.appointmentId <= 0) && n.historyAppts && n.historyAppts.length > 0 && (n.dentalLabOrderData.appointmentId = n.historyAppts[0].id);
                    i = t.find("#appoint").kendoDropDownList({
                        dataSource: u,
                        placeholder: "请选择",
                        valueTemplate: '<span class="k-state-default">#: data.startTimeStr #<\/span>',
                        template: '<span class="k-state-default">#: data.startTimeStr #<\/span>',
                        dataValueField: "id",
                        select: function(t) {
                            var i = this.dataItem(t.item.index());
                            n.dentalLabOrderData.appointmentId = i.id
                        }
                    });
                    r = i.data("kendoDropDownList")
                },
                v = function(n) {
                    var t = u.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<patient-dental-lab-order-tooth-color-select-view><\/patient-dental-lab-order-tooth-color-select-view>",
                        controller: "PatientDentalLabOrderToothColorSelectCtrl",
                        backdropClass: "ares-modal-backdrop",
                        resolve: {
                            dataHost: function() {
                                return {
                                    product: n
                                }
                            }
                        }
                    });
                    t.result.then(function(t) {
                        _.extend(n, t)
                    })
                },
                y = function(t) {
                    var i = p(t);
                    if (i) {
                        o.warn("提示", "该项目已存在列表中");
                        return
                    }
                    n.searchDealers(t.id).then(function(n) {
                        var i = w(t, n);
                        f(i)
                    })
                },
                p = function(t) {
                    var r = n.dentalLabOrderData.orders,
                        i;
                    return _.each(r, function(n) {
                        i = _.find(n.orderDetails, function(n) {
                            return n.productName == t.name && n.specification == t.specification
                        })
                    }), i
                },
                w = function(t, i) {
                    var r = [],
                        u = {
                            orgnizationId: t.dealerId,
                            orgnizationName: t.dealerName,
                            note: "",
                            salesAmount: 0,
                            id: n.acceptanceChecked ? 0 : n.dentalLabOrderId,
                            orderDetails: []
                        },
                        f = b(t, i);
                    return u.orderDetails.push(f), r.push(u), r
                },
                b = function(n, t) {
                    return {
                        toothCode: "",
                        isAreaSpecified: !1,
                        gumColorCode: "",
                        toothBodyColorCode: "",
                        toothIncisalColorCode: "",
                        productId: n.id,
                        productName: n.name,
                        specification: n.specification,
                        producerCode: n.code,
                        factoryLocation: n.factoryLocation,
                        unit: n.unit,
                        submitSource: e.SubmitSource.Office,
                        submitCount: 0,
                        salesPrice: n.salesPrice,
                        salesAmount: 0,
                        dealerPrice: n.dealerPrice,
                        note: "",
                        unityDealers: t
                    }
                },
                f = function(t) {
                    var i = n.dentalLabOrderData.orders;
                    i.length > 0 ? k(t) : n.dentalLabOrderData.orders = t
                },
                k = function(n) {
                    _.each(n, function(n) {
                        var t = n.orgnizationId;
                        h(t, n)
                    })
                },
                h = function(t, i, r) {
                    var u = d(t),
                        f = r ? r : i;
                    u > -1 ? r ? tt(u, i) : g(u, i) : n.dentalLabOrderData.orders.push(f)
                },
                d = function(t) {
                    return _.findIndex(n.dentalLabOrderData.orders, function(n) {
                        return n.orgnizationId == t
                    })
                },
                g = function(t, i) {
                    var r = n.dentalLabOrderData.orders[t],
                        u = i.orderDetails;
                    r.orderDetails = r.orderDetails.concat(u)
                },
                nt = function(t, i, r, u, e) {
                    var o, s, c;
                    t.orgnizationId = e.dealerId;
                    t.orgnizationName = e.dealerName;
                    t.orderDetails.length == 1 ? (n.dentalLabOrderData.orders.splice(i, 1), o = [t], f(o)) : (t.orderDetails.splice(u, 1), s = e.dealerId, c = r, h(s, c, t))
                },
                tt = function(t, i) {
                    var r = n.dentalLabOrderData.orders[t];
                    r.orderDetails.push(i)
                },
                it = function(n, t) {
                    c(n, t)
                },
                c = function(n, t) {
                    if (t.salesPrice !== null && t.submitCount !== null) {
                        var i = (parseFloat(t.salesPrice) * parseInt(t.submitCount)).toFixed(2);
                        i === "NaN" && (i = "0.00");
                        t.salesAmount = i;
                        n.salesAmount = parseFloat(rt(n))
                    }
                },
                rt = function(n) {
                    var t = 0;
                    return n && n.orderDetails && _.each(n.orderDetails, function(n) {
                        n && (t += parseFloat(n.salesAmount))
                    }), t
                },
                ut = function(t, i, r, u) {
                    o.confirm("提示", "确认要删除该数据？").then(function() {
                        i.orderDetails.length > 1 ? i.orderDetails.splice(r, 1) : n.dentalLabOrderData.orders.splice(u, 1)
                    })
                },
                ft = function(t) {
                    var i = t;
                    return _.each(i, function(t) {
                        t.acceptanceResult = n.acceptanceResult || 0
                    }), i
                },
                et = function(t) {
                    ot() && (i ? l(i) : n.toSave().then(function(r) {
                        i = r;
                        t == 1 ? n.$modalInstance.close(r) : l(r)
                    }))
                },
                l = function(t) {
                    var i = ft(t);
                    n.toSubmit(i)
                },
                ot = function() {
                    var t = n.dentalLabOrderData;
                    return t.appointmentId ? t.expectedFinishTime ? t.contactPhoneNumber ? t.orders.length ? (st(t), !0) : (s.error("请选择所要申请的项目"), !1) : (s.error("请填写医生联系方式"), !1) : (s.error("请选择计划返回日期"), !1) : (s.error("请选择预约时间"), !1)
                },
                st = function(n) {
                    _.each(n.orders, function(n) {
                        _.each(n.orderDetails, function(n) {
                            n.toothCode && angular.isArray(n.toothCode) && (n.toothCode = n.toothCode.join(","))
                        })
                    })
                },
                ht = function() {
                    n.dentalLabOrderId && n.getOrderDetail().then(function(t) {
                        n.dentalLabOrderData = t.data;
                        n.dentalLabOrderData && n.dentalLabOrderData.orders && n.acceptanceChecked && _.each(n.dentalLabOrderData.orders, function(n) {
                            if (n && n.orderDetails) {
                                var t = _.filter(n.orderDetails, function(n) {
                                    if (n) return n.productId > 0
                                });
                                n.orderDetails = t
                            }
                        });
                        n.dealerIds = n.dentalLabOrderData.orders[0].orgnizationId;
                        ct();
                        n.dentalLabOrderData && n.dentalLabOrderData.appointmentId && r.value(n.dentalLabOrderData.appointmentId)
                    })
                },
                ct = function() {
                    _.each(n.dentalLabOrderData.pictures, function(n) {
                        n.filePath = encodeURIComponent(n.filePath)
                    })
                },
                lt = function(n, t, i) {
                    i && n && (i.submitCount = n.length, c(t, i))
                };
            (function() {
                n.selectToothColor = v;
                n.addItemToList = y;
                n.targetType = e.PictureTargetType.DentalLabOrder;
                n.onItemNumberChange = it;
                n.onRemoveProduct = ut;
                n.switchFactory = nt;
                n.onSave = et;
                n.initAppts().then(function() {
                    a();
                    ht()
                });
                n.onToothCodeSelected = lt
            })()
        }
    }
}]);
patientModule.controller("PatientDentalLabOrderEditCtrl", ["$log", "$scope", "$modalInstance", "$q", "appointmentSvc", "loginContext", "constants", "dataHost", "patientSvc", "dentalLabSvc", "$timeout", function(n, t, i, r, u, f, e, o, s, h, c) {
    "use strict";
    var l = function() {
            var n = r.defer(),
                i = {
                    officeId: f.officeId,
                    patientId: t.dentalLabOrderData.patientId,
                    endTime: moment(Ares.today()).add(1, "d").format(e.dateFormat),
                    isCancelled: !1,
                    isPending: !1,
                    isFailed: !1
                };
            return u.searchAppointments(i).success(function(i) {
                var u, r;
                if (t.historyAppts = [], i.length > 0) {
                    for (u = angular.copy(i), r = 0; r < i.length; ++r) i[r].startTimeStr = moment(i[r].startTime).format("YYYY年MM月DD日 HH:mm");
                    t.historyAppts = t.historyAppts.concat(i)
                }
                n.resolve()
            }), n.promise
        },
        a = function() {
            var n = r.defer(),
                i;
            return t.acceptanceChecked && (t.dentalLabOrderData.orders && t.dentalLabOrderData.orders.length > 0 && (t.dentalLabOrderData.orders[0].sourceOrderId = t.dentalLabOrderId, t.dentalLabOrderData.orders[0].id = 0), t.dentalLabOrderId = 0), i = t.dentalLabOrderId ? h.updateOrder : h.createOrder, i(t.dentalLabOrderData).then(function(t) {
                var i = t.data;
                n.resolve(i)
            }), n.promise
        },
        v = function(n) {
            h.submitOrder(n).success(function(n) {
                t.$modalInstance.close(n)
            }).error(function() {
                t.$modalInstance.close()
            })
        },
        y = function() {
            var n = r.defer();
            return h.getOrderById(t.dentalLabOrderId).then(function(t) {
                n.resolve(t)
            }), n.promise
        },
        p = function(n) {
            var t = r.defer(),
                i = {
                    productIds: [n]
                };
            return h.searchDealers(i).then(function(n) {
                t.resolve(n.data)
            }), t.promise
        },
        w = function() {
            s.getPatientDentalLab(o.patientId).success(function(n) {
                t.patient = n;
                c(function() {
                    t.dentalLabOrderData && t.dentalLabOrderData.contactPhoneNumber.length <= 0 && (t.dentalLabOrderData.contactPhoneNumber = n.doctorPhone)
                })
            })
        };
    (function() {
        t.toSave = a;
        t.initAppts = l;
        t.dentalLabOrderId = o.dentalLabOrderId;
        t.acceptanceResult = o.acceptanceResult;
        t.acceptanceChecked = t.acceptanceResult ? !0 : !1;
        t.getOrderDetail = y;
        t.toSubmit = v;
        t.searchDealers = p;
        t.dentalLabOrderData = {
            patientId: o.patientId,
            contactPhoneNumber: "",
            pictures: [],
            orders: []
        };
        w()
    })()
}]);
patientModule.directive("patientDentalLabOrderLogsView", ["$window", "$log", "$timeout", "$q", function(n, t, i) {
    return {
        replace: !0,
        templateUrl: "/app/patient/views/dental-lab/dialogs/patient-dental-lab-order-logs/patient-dental-lab-order-logs-view.html",
        link: function(n, t) {
            var r = function() {
                t.parents(".modal-dialog").css("width", "440px");
                i(function() {
                    Ares.centerModal(t.closest(".modal-dialog"))
                }, 50)
            };
            (function() {
                r()
            })()
        }
    }
}]);
patientModule.controller("PatientDentalLabOrderLogsCtrl", ["$log", "$scope", "$modalInstance", "dataHost", "dentalLabSvc", function(n, t, i, r, u) {
    "use strict";
    var f = function() {
            i.dismiss()
        },
        e = function() {
            u.orderLog(t.orderId).then(function(n) {
                t.orderLogs = n.data
            })
        };
    (function() {
        t.cancel = f;
        t.orderId = r.orderId;
        t.orderNo = r.orderNo;
        e()
    })()
}]);
patientModule.directive("patientDentalLabOrderRemoveNoteView", ["$window", "$log", "$timeout", "$q", function(n, t, i) {
    return {
        replace: !0,
        templateUrl: "/app/patient/views/dental-lab/dialogs/patient-dental-lab-order-remove-note/patient-dental-lab-order-remove-note-view.html",
        link: function(n, t) {
            var r = function() {
                t.parents(".modal-dialog").css("width", "420px");
                i(function() {
                    Ares.centerModal(t.closest(".modal-dialog"))
                }, 50)
            };
            (function() {
                r()
            })()
        }
    }
}]);
patientModule.controller("PatientDentalLabOrderRemoveNoteCtrl", ["$log", "$scope", "$modalInstance", "aresNotification", function(n, t, i, r) {
    "use strict";
    var u = function() {
            i.dismiss()
        },
        f = function() {
            if (!t.note) {
                r.error("请填写删除原因！");
                return
            }
            i.close(t.note)
        };
    (function() {
        t.cancel = u;
        t.save = f
    })()
}]);
patientModule.directive("patientDentalLabOrderToothColorSelectView", ["$log", "$modal", "$timeout", "$window", "practiceSvc", function(n, t, i, r, u) {
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/views/dental-lab/dialogs/patient-dental-lab-order-tooth-color-select/patient-dental-lab-order-tooth-color-select-view.html",
        link: function(n, t) {
            "use strict";
            var r = function() {
                    t.parents(".modal-dialog").css("width", "418px");
                    i(function() {
                        Ares.centerModal(t.closest(".modal-dialog"))
                    }, 50)
                },
                f = function(i, r) {
                    var f = t.find(i);
                    u.getItemTypes(n.itemType).success(function(n) {
                        var t = f.kendoDropDownList({
                            dataSource: n,
                            dataTextField: "itemName",
                            dataValueField: "itemName",
                            optionLabel: "请选择",
                            value: r,
                            select: function() {}
                        })
                    })
                },
                e = function() {
                    var t = n.toothColorData,
                        i;
                    t.isAreaSpecified || (t.toothColorCode = t.gumColorCode);
                    i = [{
                        eleId: "#toothColor",
                        eleValue: t.toothColorCode
                    }, {
                        eleId: "#gums",
                        eleValue: t.gumColorCode
                    }, {
                        eleId: "#toothBody",
                        eleValue: t.toothBodyColorCode
                    }, {
                        eleId: "#toothTip",
                        eleValue: t.toothIncisalColorCode
                    }];
                    _.each(i, function(n) {
                        f(n.eleId, n.eleValue)
                    })
                },
                o = function(t) {
                    t.isAreaSpecified = !t.isAreaSpecified;
                    n.isAreaSpecified = t.isAreaSpecified
                };
            (function() {
                n.setEnable = o;
                n.itemType = "牙色";
                r();
                e()
            })()
        }
    }
}]);
patientModule.controller("PatientDentalLabOrderToothColorSelectCtrl", ["$log", "$scope", "$q", "$timeout", "$modalInstance", "dataHost", "aresNotification", function(n, t, i, r, u, f) {
    "use strict";
    var e = function() {
            u.dismiss()
        },
        o = function() {
            t.isAreaSpecified || (t.toothColorData.gumColorCode = t.toothColorData.toothColorCode, t.toothColorData.toothBodyColorCode = "", t.toothColorData.toothIncisalColorCode = "");
            u.close(t.toothColorData)
        };
    (function() {
        t.close = e;
        t.save = o;
        t.product = f.product;
        var n = t.product;
        t.toothColorData = _.extend({}, t.product)
    })()
}]);
patientModule.directive("disposalToothBoard", ["$log", "toothUtil", "$modal", "$timeout", function(n, t, i) {
    "use strict";
    return {
        restrict: "E",
        templateUrl: "/app/patient/views/disposal-tooth-artwork/disposal-tooth-board.html",
        scope: {
            selectedToothCodes: "=",
            selectedToothItems: "&",
            diagnoseItemName: "=",
            diagnoseNote: "=",
            diagnoseItemCode: "=",
            showDisposalDialog: "=",
            isEnableMethod: "&",
            closeToothBoard: "&"
        },
        link: function(n) {
            var t = function(t) {
                    for (var r = n.selectedToothCodes, i = 0; i < t.length; i++) r.indexOf(t[i]) > -1 || r.push(t[i])
                },
                r = function(t) {
                    n.isPrimary = t == "primary"
                },
                u = function(t) {
                    n.$apply(function() {
                        var i = n.selectedToothCodes,
                            u = n.diagnoseNote,
                            r = i.indexOf(t);
                        r > -1 ? i.splice(r, 1) : i.push(t);
                        n.selectedToothItems()
                    })
                },
                f = function() {
                    n.showDisposalDialog.isShow = !0;
                    var t = i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<disposal-dialog-view><\/disposal-dialog-view>",
                        controller: "DisposalDialogCtrl",
                        windowClass: "disposal-tooth-borard-index",
                        size: "md"
                    });
                    t.result.then(function(t) {
                        n.showDisposalDialog.isShow = !1;
                        n.diagnoseItemName = t.itemName;
                        n.diagnoseItemCode = t.itemCode
                    })
                },
                e = function() {
                    $("#toothDiv").parent().parent().parent().parent().parent().css("z-index", "1050")
                },
                o = function() {
                    n.diagnoseItemName = null;
                    n.diagnoseItemCode = null
                },
                s = function() {
                    if (n.isSelectAll == "全口") {
                        n.isSelectAll = "重置";
                        n.selectedToothCodes.splice(0, n.selectedToothCodes.length);
                        var i = n.selectedToothCodes;
                        n.isPrimary ? (t(n.primaryQuadrant1), t(n.primaryQuadrant2), t(n.primaryQuadrant3), t(n.primaryQuadrant4)) : (t(n.secondaryQuadrant1), t(n.secondaryQuadrant2), t(n.secondaryQuadrant3), t(n.secondaryQuadrant4));
                        n.selectedToothItems()
                    } else n.isSelectAll = "全口", n.selectedToothCodes.splice(0, n.selectedToothCodes.length), n.selectedToothItems()
                },
                h = function() {
                    n.isSelectAll = "全口";
                    n.selectedToothCodes.splice(0, n.selectedToothCodes.length);
                    n.selectedToothItems()
                },
                c = function() {
                    n.isPrimary ? t(n.primaryQuadrant1) : t(n.secondaryQuadrant1);
                    n.selectedToothItems()
                },
                l = function() {
                    n.isPrimary ? t(n.primaryQuadrant2) : t(n.secondaryQuadrant2);
                    n.selectedToothItems()
                },
                a = function() {
                    n.isPrimary ? t(n.primaryQuadrant4) : t(n.secondaryQuadrant4);
                    n.selectedToothItems()
                },
                v = function() {
                    n.isPrimary ? t(n.primaryQuadrant3) : t(n.secondaryQuadrant3);
                    n.selectedToothItems()
                };
            (function() {
                n.secondaryQuadrant1 = ["11", "12", "13", "14", "15", "16", "17", "18"].reverse();
                n.secondaryQuadrant2 = ["21", "22", "23", "24", "25", "26", "27", "28"];
                n.secondaryQuadrant3 = ["31", "32", "33", "34", "35", "36", "37", "38"];
                n.secondaryQuadrant4 = ["41", "42", "43", "44", "45", "46", "47", "48"].reverse();
                n.primaryQuadrant1 = ["51", "52", "53", "54", "55"].reverse();
                n.primaryQuadrant2 = ["61", "62", "63", "64", "65"];
                n.primaryQuadrant3 = ["71", "72", "73", "74", "75"];
                n.primaryQuadrant4 = ["81", "82", "83", "84", "85"].reverse();
                n.isSelectAll = n.selectedToothCodes.length == 32 && !n.isPrimary || n.selectedToothCodes.length == 20 && n.isPrimary ? "重置" : "全口";
                e();
                n.selectAll = s;
                n.clearDisposal = o;
                n.onDoubleClickDisposalItemInput = f;
                n.isPrimary = !1;
                n.switchTooth = r;
                n.toggleSelect = u;
                n.clearTooth = h;
                n.selectUR = c;
                n.selectUL = l;
                n.selectLR = a;
                n.selectLL = v
            })()
        }
    }
}]);
patientModule.directive("disposalToothCode", ["$log", "toothUtil", function() {
    "use strict";
    return {
        restrict: "E",
        templateUrl: "/app/patient/views/disposal-tooth-artwork/disposal-tooth-code.html",
        scope: !0,
        link: function(n) {
            var t = function() {
                n.toothSelector.toggleTooth(n.tooth)
            };
            (function() {
                n.isSelectable = n.toothSelector != null;
                n.toggleTooth = t
            })()
        }
    }
}]);
patientModule.directive("disposalToothCondition", ["$log", function(n) {
    "use strict";
    return n.debug("disposalToothCondition.ctor()..."), {
        restrict: "E",
        templateUrl: "/app/patient/views/disposal-tooth-artwork/disposal-tooth-condition.html",
        controller: ["$scope", function() {
            (function() {})()
        }],
        scope: {
            toothNumber: "@",
            isReadOnly: "="
        },
        link: function() {}
    }
}]);
patientModule.directive("disposalToothImageLite", ["$log", "$timeout", "toothUtil", function(n, t, i) {
    return {
        restrict: "E",
        template: function(n, t) {
            return t.arch == "upper" ? '<div class="tooth-image-lite-container" style="max-width: 30px;max-height: 80px;"><img ng-src="{{imgSrc}}" style="max-width: 30px;max-height: 50px;" /><div class="tooth-image-lite-tooth-code"><a id="quadrantCode" class="btn btn-sm btn-default">{{quadrantCode}}<\/a><\/div><\/div>' : '<div class="tooth-image-lite-container" style="max-width: 30px;max-height: 80px;"><div class="tooth-image-lite-tooth-code"><a id="quadrantCode" class="btn btn-sm btn-default">{{quadrantCode}}<\/a><\/div><img ng-src="{{imgSrc}}"  style="max-width: 30px;max-height: 50px;" /><\/div>'
        },
        scope: {
            toothCode: "@",
            selectedToothCodes: "=",
            toggleSelect: "="
        },
        link: function(n, t) {
            var u = function() {
                    $(t).click(function() {
                        r();
                        n.toggleSelect(n.toothCode)
                    })
                },
                r = function() {
                    var n = $(t);
                    n.children().toggleClass("tooth-image-lite-selected");
                    n.find("#quadrantCode").toggleClass("btn-primary")
                },
                f = function() {
                    n.selectedToothCodes && n.selectedToothCodes.indexOf(n.toothCode) > -1 && r()
                };
            (function() {
                n.quadrantCode = i.getQuadrantCode(n.toothCode);
                n.imgSrc = "/app-resource/images/small-tooth/Tooth_" + n.toothCode + "_Facial.png";
                n.$watchCollection("selectedToothCodes", function() {
                    var r, i;
                    if (n.selectedToothCodes)
                        if (n.selectedToothCodes.length == 0) i = $(t), i.children().removeClass("tooth-image-lite-selected"), i.find("#quadrantCode").removeClass("btn-primary");
                        else
                            for (r = 0; r < n.selectedToothCodes.length; r++) n.selectedToothCodes[r] == n.toothCode && (i = $(t), i.children().addClass("tooth-image-lite-selected"), i.find("#quadrantCode").addClass("btn-primary"))
                });
                u();
                f()
            })()
        }
    }
}]);
patientModule.directive("disposalToothSelector", ["$log", "$document", "toothUtil", function(n, t, i) {
    "use strict";
    return {
        restrict: "E",
        templateUrl: "/app/patient/views/disposal-tooth-artwork/disposal-tooth-selector.html",
        scope: {
            selectedToothCodes: "=",
            selectedToothItem: "&",
            popoverPlacement: "@",
            diagnoseItem: "=",
            isEnableMethod: "&"
        },
        link: function(r) {
            var u = Ares.globalEventUtil(t),
                o = function(n) {
                    h(n);
                    r.isToothBoardOpened = r.disableBtn ? !1 : !0;
                    u.onMousedown(s)
                },
                f = function() {
                    r.isToothBoardOpened = !1;
                    u.offMousedown()
                };
            r.showDisposalDialog = {
                isShow: !1
            };
            var s = function(n) {
                    if (!r.showDisposalDialog.isShow) {
                        var t = $(n.target).parents(".popover").length;
                        t || r.$apply(function() {
                            f()
                        })
                    }
                },
                e = function() {
                    var n = [
                            [],
                            [],
                            [],
                            []
                        ],
                        t, u;
                    r.selectedToothCodes && (t = _.map(r.selectedToothCodes, function(n) {
                        return i.getTooth(n)
                    }), u = t.sort(i.compareTooth), angular.forEach(u, function(t) {
                        var i = t.getQuadrant(),
                            r = t.getQuadrantCode();
                        n[i - 1].push(r)
                    }));
                    r.quadrant1Text = n[0].reverse().join("");
                    r.quadrant2Text = n[1].join("");
                    r.quadrant3Text = n[2].join("");
                    r.quadrant4Text = n[3].reverse().join("")
                },
                h = function(n) {
                    var t = n.screenX,
                        i = n.offsetX,
                        u = t - i,
                        f = u > 610;
                    r.popoverPlacement = f ? "left" : "right"
                };
            (function() {
                r.popoverPlacement = r.popoverPlacement || "left";
                r.toothBoardUrl = "toothBoard.html";
                r.isToothBoardOpened = !1;
                r.openToothBoard = o;
                r.closeToothBoard = f;
                r.selectedToothItem = r.selectedToothItem;
                r.selectedToothCodes = r.selectedToothCodes || [];
                _.isArray(r.selectedToothCodes) || (n.error("[disposal-tooth-selector]: selectedToothCodes is not an array."), r.selectedToothCodes = []);
                r.$watchCollection("selectedToothCodes", function() {
                    e()
                });
                r.$on("$destroy", function() {
                    u.dispose()
                });
                e()
            })()
        }
    }
}]);
patientModule.directive("patientLisorderEditView", ["$log", "$timeout", "$modal", "practiceSvc", "patientSvc", "appointmentSvc", "loginContext", "constants", "aresDialog", "chargeItemSvc", function(n, t, i, r, u, f, e, o, s, h) {
    "use strict";
    return {
        templateUrl: "/app/patient/views/lisorder/patient-lisorder-edit-view.html",
        controller: "PatientLisorderEditCtrl",
        link: function(n, t) {
            n.office = {};
            n.isShowTree = !0;
            n.systemSettingItems = {};
            n.chargeItemCatagories = {};
            n.chargeItems = {};
            n.currentLisOrder = {};
            n.selectLisOrderItem = null;
            var l = !1,
                w = function() {
                    var n = $(window).height() - 250;
                    $("#itemlist").css("height", n)
                },
                b = function() {
                    n.isShowTree = !1;
                    $("#treeDiv").css("width", "0px");
                    $("#treeDiv").removeClass("col-md-3");
                    $("#listDiv").css("width", "95%");
                    $("#listDiv").removeClass("col-md-8")
                },
                k = function() {
                    n.isShowTree = !0;
                    $("#treeDiv").css("width", "");
                    $("#treeDiv").addClass("col-md-3");
                    $("#listDiv").css("width", "");
                    $("#listDiv").addClass("col-md-8")
                },
                d = function() {
                    l = !0;
                    var i = t.find("#lisorderDetailGrid"),
                        r = i.kendoGrid({
                            dataSource: {
                                data: n.currentLisOrder.laboratoryOrderDetailList,
                                schema: {
                                    model: {
                                        id: "id",
                                        fields: {
                                            itemName: {
                                                type: "string",
                                                editable: !1
                                            },
                                            price: {
                                                type: "number",
                                                editable: !1
                                            },
                                            unit: {
                                                type: "string",
                                                editable: !1
                                            },
                                            count: {
                                                type: "number",
                                                validation: {
                                                    min: 0
                                                }
                                            },
                                            notes: {
                                                type: "string"
                                            },
                                            detailStatus: {
                                                type: "string",
                                                editable: !1
                                            }
                                        }
                                    }
                                }
                            },
                            scrollable: !1,
                            editable: n.editstatus == 1,
                            selectable: "single",
                            model: {
                                id: "id"
                            },
                            columns: [{
                                field: "itemName",
                                title: "项目名称",
                                width: "200px"
                            }, {
                                field: "price",
                                title: "单价",
                                width: "50px"
                            }, {
                                field: "unit",
                                title: "单位",
                                width: "40px"
                            }, {
                                field: "count",
                                title: "数量",
                                width: "60px"
                            }, {
                                field: "notes",
                                title: "备注",
                                width: "50px"
                            }, {
                                field: "detailStatus",
                                title: "状态",
                                width: "50px"
                            }, {
                                command: {
                                    text: "删除",
                                    click: n.detailDelete
                                },
                                title: "操作",
                                width: "50px"
                            }]
                        }).data("kendoGrid")
                },
                a = function() {
                    var i = t.find("#lisorderDetailGrid"),
                        r = i.data("kendoGrid");
                    r.dataSource.data(n.currentLisOrder.laboratoryOrderDetailList)
                },
                v = function() {
                    r.getDoctors().success(function(t) {
                        var r, i;
                        if ($("#doctor").kendoNameCodeFilterComboBox({
                                dataSource: t,
                                filter: "contains",
                                placeholder: "请选择医生",
                                dataTextField: "name",
                                dataValueField: "id",
                                select: function(t) {
                                    var i = this.dataItem(t.item.index());
                                    n.currentLisOrder.doctorName = i.name;
                                    n.currentLisOrder.doctorId = i.id
                                }
                            }), r = $("#doctor").data("kendoNameCodeFilterComboBox"), r)
                            if (n.currentLisOrder && n.currentLisOrder.doctorId) {
                                for (i = 0; i < t.length; ++i)
                                    if (t[i].id == n.currentLisOrder.doctorId) {
                                        r.select(i);
                                        break
                                    }
                            } else
                                for (i = 0; i < t.length; ++i)
                                    if (t[i].id == e.providerId) {
                                        r.select(i);
                                        n.currentLisOrder.doctorName = t[i].name;
                                        n.currentLisOrder.doctorId = t[i].id;
                                        break
                                    }
                    })
                },
                g = function(t) {
                    var r, i;
                    if (t.preventDefault(), n.currentLisOrder.orderStatus != "未提交") {
                        n.showInfoNotification("无法编辑已提交的申请单！");
                        return
                    }
                    for (r = this.dataItem($(t.currentTarget).closest("tr")), i = 0; i < n.currentLisOrder.laboratoryOrderDetailList.length; ++i)
                        if (n.currentLisOrder.laboratoryOrderDetailList[i].itemName == r.itemName) {
                            n.currentLisOrder.laboratoryOrderDetailList.splice(i, 1);
                            break
                        }
                    n.refreshDataSource()
                };
            n.browserChargeItemSetting = function() {
                h.getChargeItemCategoryList().success(function(t) {
                    n.chargeItemCatagories = t;
                    r.listChargeItems().success(function(t) {
                        n.chargeItems = t;
                        n.constructChargeDetailTreeData();
                        n.constructQuickSearchComboBox()
                    }).error(function(t) {
                        n.data.error = t
                    })
                })
            };
            n.constructQuickSearchComboBox = function() {
                $("#chargeItemSearch").kendoItemNameCodeFilterComboBox({
                    filter: "contains",
                    placeholder: "请输入拼首码/项目编码快速查询",
                    dataTextField: "treeLabelText",
                    dataValueField: "id",
                    headerTemplate: '<div class="dropdown-select-head" style=" border-width: 0 0 1px 0;text-transform: uppercase;background-color:#f4f4f4;border-bottom: 1px solid #e3e3e3;" ><span style=" display: inline-block;width:70px;max-width:70px;margin-left:10px;padding:5px">项目编码<\/span><span style=" display: inline-block;width:180px;max-width:180px">项目名称<\/span><span style=" display: inline-block;width:50px;max-width:50px">单价<\/span><\/div>',
                    template: '<span class="dropdown-select-text" style=" display: inline-block;width:70px;max-width:70px;margin-left:10px;">#: data.procedureCode==null ? "" :data.procedureCode #<\/span><span class="dropdown-select-text" style=" display: inline-block;width:200px;max-width:180px;">#: data.itemName #<\/span><span class="dropdown-select-text" style=" display: inline-block;width:50px;max-width:50px">#: data.price #<\/span>',
                    dataSource: n.chargeItems,
                    height: 370,
                    select: function(t) {
                        var i = this.dataItem(t.item.index());
                        n.selectLisOrderItem = i
                    },
                    change: function() {
                        if (n.selectLisOrderItem != null) {
                            if (this.value(""), n.currentLisOrder.laboratoryOrderDetailList || (n.currentLisOrder.laboratoryOrderDetailList = []), n.currentLisOrder.viewStatus == "browser") {
                                n.showInfoNotification("浏览模式下，无法编辑医嘱！");
                                return
                            }
                            var t = {};
                            t.id = 0;
                            t.itemName = n.selectLisOrderItem.itemName;
                            t.unit = n.selectLisOrderItem.unit;
                            t.allowDiscount = n.selectLisOrderItem.allowDiscount;
                            t.allowOrderDiscount = n.selectLisOrderItem.allowDiscount;
                            t.count = 1;
                            t.price = n.selectLisOrderItem.price;
                            t.totalPrice = n.selectLisOrderItem.price;
                            t.chargeItemId = n.selectLisOrderItem.id;
                            t.procedureCode = n.selectLisOrderItem.procedureCode;
                            n.selectLisOrderItem = null;
                            n.currentLisOrder.laboratoryOrderDetailList.push(t);
                            n.refreshDataSource()
                        }
                    }
                })
            };
            n.constructChargeDetailTreeData = function() {
                for (var i, t = 0; t < n.chargeItemCatagories.length; ++t) n.chargeItemCatagories[t].chargeItems = [];
                for (t = 0; t < n.chargeItems.length; ++t)
                    for (i = 0; i < n.chargeItemCatagories.length; ++i) n.chargeItems[t].itemCatagoryId == n.chargeItemCatagories[i].id && (n.chargeItems[t].treeLabelText = n.chargeItems[t].itemName + " ,  " + n.chargeItems[t].price + " 元 ", n.chargeItemCatagories[i].chargeItems.push(n.chargeItems[t]));
                n.chargeItemFullTreeData = new kendo.data.HierarchicalDataSource({
                    data: n.chargeItemCatagories,
                    schema: {
                        model: {
                            children: "chargeItems"
                        }
                    }
                })
            };
            n.onDoubleClickChargeItemFullTree = function(t) {
                var r, u, i;
                if (n.currentLisOrder.orderStatus != "未提交") {
                    n.showInfoNotification("无法编辑已提交的申请单！");
                    return
                }
                if (r = this.chargeItemFullTree.dataItem(t.target), r.parentNode()) {
                    if (n.currentLisOrder.laboratoryOrderDetailList || (n.currentLisOrder.laboratoryOrderDetailList = []), u = _.find(n.currentLisOrder.laboratoryOrderDetailList, function(n) {
                            return n.itemName == r.itemName ? !0 : !1
                        }), u) {
                        n.showInfoNotification("此项目已经在医嘱中！");
                        return
                    }
                    i = {};
                    i.id = 0;
                    i.itemName = r.itemName;
                    i.unit = r.unit;
                    i.allowDiscount = r.allowDiscount;
                    i.allowOrderDiscount = r.allowDiscount;
                    i.count = 1;
                    i.price = r.price;
                    i.totalPrice = r.price;
                    i.chargeItemId = r.id;
                    i.itemType = r.parentNode().itemName;
                    i.procedureCode = r.procedureCode;
                    i.detailStatus = "未提交";
                    n.currentLisOrder.laboratoryOrderDetailList.push(i);
                    n.refreshDataSource()
                }
            };
            var y = function() {
                    r.getDepartment().success(function(t) {
                        var r, i;
                        if ($("#department").kendoDropDownList({
                                dataSource: t,
                                dataTextField: "itemName",
                                dataValueField: "itemName",
                                select: function(t) {
                                    var i = this.dataItem(t.item.index());
                                    n.currentLisOrder.departmentName = i.itemName
                                }
                            }), r = $("#department").data("kendoDropDownList"), r)
                            if (n.currentLisOrder && n.currentLisOrder.departmentName) {
                                for (i = 0; i < t.length; ++i)
                                    if (t[i].itemName == n.currentLisOrder.departmentName) {
                                        r.select(i);
                                        break
                                    }
                            } else t.length > 0 && (r.select(0), n.currentLisOrder.departmentName = t[0].itemName)
                    })
                },
                c = function() {
                    var t = {
                        officeId: e.officeId,
                        patientId: n.patientId,
                        endTime: moment(Ares.today()).add(1, "d").format(o.dateFormat),
                        isCancelled: !1,
                        isPending: !1
                    };
                    e.roles.indexOf("牙医") > -1 && n.currentLisOrder.viewstatus != 0 && (t.doctorId = e.providerId);
                    n.currentLisOrder.viewstatus == 0 ? f.getPatientAppts(n.patientId).success(function(t) {
                        var i, r;
                        if (t.length > 0 && (n.historyAppts = t), n.historyAppts != null) {
                            for (i = 0; i < n.historyAppts.length; ++i) n.historyAppts[i].startTimeStr = moment(n.historyAppts[i].startTime).format("YYYY-MM-DD"), n.historyAppts[i].startTime = moment(n.historyAppts[i].startTime).format("YYYY年MM月DD日 HH:mm");
                            ($("#appoint").kendoDropDownList({
                                dataSource: n.historyAppts,
                                placeholder: "请选择",
                                valueTemplate: '<span class="k-state-default">#: data.startTime #<\/span>',
                                template: '<span class="k-state-default">#: data.startTime #<\/span>',
                                dataValueField: "id",
                                select: function() {}
                            }), r = $("#appoint").data("kendoDropDownList"), r) && (!n.currentLisOrder.doctorId || n.currentLisOrder.doctorId != 0)
                        }
                    }) : f.searchAppointmentsByTenant(t).success(function(t) {
                        for (var u, h, l, f, c = [], r = 0; r < t.length; r++) t[r].startTime >= moment(Ares.today()).format(o.dateFormat) && c.push(t[r]);
                        for (c.length == 0 && t.length != 0 ? (n.historyAppts = t, s.confirm("提醒", "今天没有预约，是否要创建今天的预约？").then(function() {
                                var t = moment(),
                                    i = moment().format("mm") * 1;
                                i < 15 ? t.minutes(15) : i > 15 && i < 30 ? t.minutes(30) : i > 30 && i < 45 ? t.minutes(45) : i > 45 && (t.minutes(0), t.add(1, "hour"));
                                var r = moment(t).format("YYYY-MM-DD HH:mm"),
                                    f = moment(r).add(30, "m").format("YYYY-MM-DD HH:mm"),
                                    u = {
                                        startTime: r,
                                        endTime: f,
                                        patientId: n.patientId,
                                        isFirstVisit: !0
                                    };
                                e.roles.indexOf("牙医") > -1 && (u.doctorId = e.providerId);
                                p(u)
                            })) : t.length > 0 ? n.historyAppts = t : (n.historyAppts = null, s.confirm("提醒", "当天患者没有预约关联您，是否为当前患者创建一个医生为您的新预约？").then(function() {
                                var t = moment(),
                                    i = moment().format("mm") * 1;
                                i < 15 ? t.minutes(15) : i > 15 && i < 30 ? t.minutes(30) : i > 30 && i < 45 ? t.minutes(45) : i > 45 && (t.minutes(0), t.add(1, "hour"));
                                var r = moment(t).format("YYYY-MM-DD HH:mm"),
                                    f = moment(r).add(30, "m").format("YYYY-MM-DD HH:mm"),
                                    u = {
                                        startTime: r,
                                        endTime: f,
                                        patientId: n.patientId,
                                        isFirstVisit: !0
                                    };
                                e.roles.indexOf("牙医") > -1 && (u.doctorId = e.providerId);
                                p(u)
                            }, function() {
                                appNav.switchState("patientLisOrder.historyRecords", {
                                    patientId: n.patientId
                                })
                            })), u = angular.copy(t), h = [], r = 0; r < u.length; r++) u[r].startTime >= moment(Ares.today()).format(o.dateFormat) && u[r].startTime < moment(Ares.today()).add(1, "d").format(o.dateFormat) && h.push(u[r]);
                        if (n.currentLisOrder.viewstatus != 0 && n.currentLisOrder.id == 0 && h.length > 1 && (l = i.open({
                                animation: !0,
                                backdrop: "static",
                                template: "<appt-list-dialog><\/appt-list-dialog>",
                                controller: "apptListDialogCtrl",
                                size: "md",
                                resolve: {
                                    host: function() {
                                        return {
                                            apptList: h,
                                            patientId: n.patientId,
                                            type: "lis"
                                        }
                                    }
                                }
                            }), l.result.then(function(t) {
                                for (var i = 0; i < n.historyAppts.length; ++i)
                                    if (n.historyAppts[i].id == t.id) {
                                        f.select(i);
                                        break
                                    }
                            })), n.historyAppts != null) {
                            for (r = 0; r < n.historyAppts.length; ++r) n.historyAppts[r].startTimeStr = moment(n.historyAppts[r].startTime).format("YYYY-MM-DD"), n.historyAppts[r].startTime = moment(n.historyAppts[r].startTime).format("YYYY年MM月DD日 HH:mm");
                            if (($("#appoint").kendoDropDownList({
                                    dataSource: n.historyAppts,
                                    placeholder: "请选择",
                                    valueTemplate: '<span class="k-state-default">#: data.startTime #<\/span>',
                                    template: '<span class="k-state-default">#: data.startTime #<\/span>',
                                    dataValueField: "id",
                                    select: function(t) {
                                        var i = this.dataItem(t.item.index());
                                        n.currentLisOrder.appointId = i.id;
                                        n.visitingTime = i
                                    }
                                }), f = $("#appoint").data("kendoDropDownList"), f) && (!n.currentLisOrder.doctorId || n.currentLisOrder.doctorId != 0))
                                if (n.currentLisOrder.appointId && n.currentLisOrder.appointId != 0)
                                    for (r = 0; r < n.historyAppts.length; ++r) n.historyAppts[r].id == n.currentLisOrder.appointId && f.select(r);
                                else f.select(0)
                        }
                    })
                },
                p = function(n) {
                    f.createAppointment(n).success(function() {
                        c()
                    })
                },
                nt = function() {
                    n.validateOrder() != !1 && (n.currentLisOrder.id == 0 ? u.createLisOrder(n.currentLisOrder).success(function(t) {
                        n.currentLisOrder.id = t.id;
                        n.currentLisOrder.orderNo = t.orderNo;
                        n.showNotification("保存成功！")
                    }) : u.updateLisOrder(n.currentLisOrder).success(function() {
                        n.showNotification("保存成功！")
                    }))
                },
                tt = function() {
                    var r = $("#doctor").data("kendoNameCodeFilterComboBox"),
                        u, f, o, i, e;
                    return r.select() == -1 ? (n.showErrorNotification("请选择一个申请医生！"), !1) : (n.currentLisOrder.doctorName = r.text(), n.currentLisOrder.doctorId = r.value(), u = $("#appoint").data("kendoDropDownList"), !u) ? (n.showErrorNotification("没有关联的就诊时间，请先创建一次预约！"), !1) : (n.currentLisOrder.appointId = u.value(), !n.currentLisOrder.appointId) ? (n.showErrorNotification("没有关联的就诊时间，请先创建一次预约！"), !1) : (f = $("#department").data("kendoDropDownList"), f && (n.currentLisOrder.departmentName = f.text()), o = t.find("#lisorderDetailGrid"), i = o.data("kendoGrid"), !i) ? (n.showErrorNotification("保存失败!"), !1) : (i.saveChanges(), e = i.dataSource.data(), e.length == 0) ? (n.showErrorNotification("请先添加检验项目!"), !1) : (_.each(e, function(t, i) {
                        n.currentLisOrder.laboratoryOrderDetailList[i].count = t.count;
                        n.currentLisOrder.laboratoryOrderDetailList[i].notes = t.notes
                    }), !0)
                },
                it = function() {
                    n.validateOrder() != !1 && u.submitLisOrder(n.currentLisOrder).success(function(t) {
                        n.currentLisOrder.id = t.id;
                        n.currentLisOrder.orderStatus = t.orderStatus;
                        n.currentLisOrder.orderNo = t.orderNo;
                        _.each(n.currentLisOrder.laboratoryOrderDetailList, function(n) {
                            n.detailStatus = "已提交"
                        });
                        n.refreshDataSource();
                        n.showNotification("提交成功！")
                    })
                };
            (function() {
                w();
                n.showTree = k;
                n.hideTree = b;
                n.refreshDataSource = a;
                n.detailDelete = g;
                n.editGrid = n.editstatus && n.editstatus == 0 ? !1 : !0;
                n.validateOrder = tt;
                n.saveLisOrder = nt;
                n.submitLisOrder = it;
                n.editstatus == 1 ? n.browserChargeItemSetting() : n.hideTree();
                u.getPatient(n.patientId).success(function(t) {
                    n.patient = t;
                    n.currentOrderId > 0 ? u.getLisOrder(n.currentOrderId).success(function(t) {
                        n.currentLisOrder = t;
                        n.currentLisOrder.viewStatus = n.editstatus && n.editstatus == 0 ? "browser" : "edit";
                        c();
                        v();
                        y()
                    }) : n.currentOrderId == 0 && (n.currentLisOrder = {
                        id: 0,
                        patientId: n.patientId,
                        doctorId: 0,
                        doctorName: "",
                        orderStatus: "未提交",
                        comments: ""
                    }, n.currentLisOrder.viewStatus = "edit", c(), v(), y())
                });
                n.$watch("currentLisOrder.laboratoryOrderDetailList", function() {
                    l ? a() : d()
                })
            })()
        }
    }
}]);
patientModule.directive("patientLisorderTableView", ["$log", "$timeout", "$window", "permissionProvider", function(n, t, i, r) {
    "use strict";
    return {
        templateUrl: "/app/patient/views/lisorder/patient-lisorder-table-view.html",
        controller: "PatientLisorderCtrl",
        link: function(n, t) {
            var e = Ares.kendoGridUtil(i, n),
                u = !1,
                o = function() {
                    if (n.lisOrders) {
                        u = !0;
                        n.gridColumns = [];
                        n.$root.isRegularChain && n.gridColumns.push({
                            field: "officeName",
                            title: "诊所",
                            width: "100px"
                        });
                        n.gridColumns.push({
                            field: "orderNo",
                            title: "申请单编号",
                            width: "60px"
                        }, {
                            field: "recordCreatedTime",
                            title: "申请创建时间",
                            width: "130px",
                            template: "#: moment(recordCreatedTime).format('YYYY年MM月DD日 HH:mm') #"
                        }, {
                            field: "doctorName",
                            title: "医生",
                            width: "60px"
                        }, {
                            field: "orderStatus",
                            title: "申请状态",
                            width: "40px"
                        }, {
                            field: "chargeOrderStatus",
                            title: "收费状态",
                            width: "40px"
                        }, {
                            field: "submitDataTime",
                            title: "申请提交时间",
                            width: "130px",
                            template: "#:submitDataTime?moment(submitDataTime).format('YYYY年MM月DD日 HH:mm'):''#"
                        }, {
                            template: e.commandTemplate,
                            title: "",
                            width: "50px"
                        });
                        var i = t.find("#lisorderList");
                        i.kendoGrid({
                            dataSource: {
                                data: n.lisOrders
                            },
                            scrollable: !1,
                            sortable: !0,
                            selectable: "single",
                            model: {
                                id: "id"
                            },
                            columns: n.gridColumns
                        })
                    }
                },
                s = function() {
                    var n = [{
                        text: "编辑",
                        action: "editLisOrder",
                        icon: "glyphicon-edit"
                    }, ];
                    return r.isAllowed("patientOutProcess.delete") && n.push({
                        text: "作废",
                        action: "discardLisOrder",
                        icon: "glyphicon-trash"
                    }), n
                },
                f = function(t) {
                    return _.find(n.lisOrders, function(n) {
                        return n.id == t
                    })
                },
                h = function(t, i, r) {
                    n.$apply(function() {
                        var t = f(r);
                        switch (i) {
                            case "editLisOrder":
                                n.editLisOrder(t);
                                break;
                            case "discardLisOrder":
                                n.discardLisOrder(t)
                        }
                    })
                },
                c = function() {
                    if (n.lisOrders) {
                        var r = t.find("#lisorderList"),
                            i = r.data("kendoGrid");
                        i && i.dataSource.data(n.lisOrders)
                    }
                };
            (function() {
                n.commands = s();
                n.onCommandClick = h;
                n.findOrder = f;
                n.$watch("lisOrders", function() {
                    u ? c() : o()
                })
            })()
        }
    }
}]);
patientModule.directive("patientLisorderView", ["$log", "$timeout", "$state", "$modal", "appNav", "enums", "eventAggregator", "practiceSvc", function(n, t, i, r, u) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/views/lisorder/patient-lisorder-view.html",
        controller: "PatientLisorderCtrl",
        scope: {
            patientId: "="
        },
        link: function(n) {
            var t = function(n) {
                    u.switchState(n, i)
                },
                i = function() {
                    var t = n.patientId;
                    return {
                        patientId: t
                    }
                };
            (function() {
                n.switchState = t
            })()
        }
    }
}]);
patientModule.directive("outprocessFixedDentureView", ["$log", "$timeout", "$modal", "practiceSvc", "patientSvc", "appointmentSvc", "appNav", "aresDialog", function(n, t, i, r, u, f, e, o) {
    "use strict";
    return {
        templateUrl: "/app/patient/views/outprocess/outprocess-fixed-denture-view.html",
        controller: "OutprocessFixedDentureCtrl",
        link: function(n, t) {
            var s = function() {
                    return i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<system-setting-item-edit><\/system-setting-item-edit>",
                        controller: "SystemSettingItemEditCtrl",
                        resolve: {
                            host: function() {
                                return {
                                    itemType: n.itemType
                                }
                            },
                            boxTitle: function() {
                                return n.boxTitle
                            }
                        }
                    })
                },
                h = function() {
                    var r, i;
                    if (n.statuses && n.statuses.length && ($("#orderStatus").kendoDropDownList({
                            dataSource: n.statuses,
                            placeholder: "请选择订单状态",
                            dataTextField: "itemName",
                            dataValueField: "id",
                            select: function(t) {
                                var i = this.dataItem(t.item.index());
                                n.currentOutprocessOrder.status = i.name
                            }
                        }), r = t.find("#orderStatus").data("kendoDropDownList"), r))
                        if (n.currentOutprocessOrder && n.currentOutprocessOrder.status) {
                            for (i = 0; i < n.statuses.length; ++i)
                                if (n.statuses[i].itemName == n.currentOutprocessOrder.status) {
                                    r.select(i);
                                    break
                                }
                        } else r.select(0)
                },
                c = function(n) {
                    var t = i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<ares-image-dialog><\/ares-image-dialog>",
                        controller: "AresImageDialogCtrl",
                        resolve: {
                            host: function() {
                                return {
                                    picture: n
                                }
                            }
                        }
                    })
                },
                l = function() {
                    return n.currentOutprocessOrder && n.currentOutprocessOrder.networkOrderId != "" && n.currentOutprocessOrder.networkOrderId != null ? !1 : !0
                },
                a = function() {
                    return n.currentOutprocessOrder && n.currentOutprocessOrder.id > 0 ? !0 : !1
                },
                v = function() {
                    return n.currentOutprocessOrder ? n.currentOutprocessOrder && n.currentOutprocessOrder.networkOrderId != "" && n.currentOutprocessOrder.networkOrderId != null ? !0 : n.currentOutprocessOrder && n.currentOutprocessOrder.id < 1 ? !1 : !1 : !1
                },
                y = function() {
                    if (!n.currentOutprocessOrder) return !1;
                    if (n.currentOutprocessOrder.id == 0) return n.showErrorNotification("请先保存订单后，再发送图片！"), !1;
                    if (!n.pictureList || n.pictureList.length == 0) return !1;
                    var t = [];
                    _.each(n.pictureList, function(n) {
                        n.status != "已发送" && t.push(n.id)
                    });
                    t.length > 0 && u.sendOutProcessPictureList(t).success(function(t) {
                        t == !0 ? n.showNotification("图片发送成功！") : n.showErrorNotification("图片发送失败！");
                        n.refreshPictureList()
                    })
                },
                p = function() {
                    var f = t.find("#doctor").data("kendoDropDownList"),
                        r, i, e, s;
                    if ((n.currentOutprocessOrder.doctorName = f.text(), n.currentOutprocessOrder.doctorId = f.value(), r = t.find("#appoint").data("kendoDropDownList"), !r) || (n.currentOutprocessOrder.appointmentId = r.value(), !n.currentOutprocessOrder.appointmentId)) return n.showErrorNotification("没有关联的就诊时间，请先创建预约，再保存订单！"), !1;
                    if (n.currentOutprocessOrder.orderDetailList.length == 0) return n.showErrorNotification("请先添加一个产品！"), !1;
                    for (i = 0; i < n.currentOutprocessOrder.orderDetailList.length; ++i) {
                        if (n.currentOutprocessOrder.orderDetailList[i].fdiToothCodesArray.length == 0) return n.showErrorNotification("加工产品必须选择对应牙位！"), !1;
                        n.currentOutprocessOrder.orderDetailList[i].fDIToothCodes = n.currentOutprocessOrder.orderDetailList[i].fdiToothCodesArray.join(",")
                    }
                    n.currentOutprocessOrder.sendDate = moment(n.currentOutprocessOrder.sendDate).format("YYYY-MM-DD HH:mm");
                    n.currentOutprocessOrder.backDate = moment(n.currentOutprocessOrder.backDate).format("YYYY-MM-DD HH:mm");
                    n.currentOutprocessOrder.tryDateTime && (n.currentOutprocessOrder.tryDateTime = moment(n.currentOutprocessOrder.tryDateTime).format("YYYY-MM-DD HH:mm"));
                    e = t.find("#supplyers").data("kendoDropDownList");
                    n.currentOutprocessOrder.supplyName = e.text();
                    s = t.find("#orderStatus").data("kendoDropDownList");
                    n.currentOutprocessOrder.status = s.text();
                    n.saveOrderDetail();
                    n.currentOutprocessOrder.id == 0 ? u.createOutProcessOrder(n.currentOutprocessOrder).success(function(t) {
                        n.currentOutprocessOrder.id = t.id;
                        o.confirm("订单发送", "您确定要将订单发往技加工厂" + n.currentOutprocessOrder.supplyName + "？").then(function() {
                            u.sendOutProcessOrder(n.currentOutprocessOrder).success(function(t) {
                                t.result == "Success" ? (n.showNotification("发送成功！"), n.currentOutprocessOrder.networkOrderId = t.orderID) : n.showErrorNotification("发送失败！")
                            }).error(function() {
                                n.showErrorNotification("发送失败！")
                            })
                        })
                    }).error(function() {
                        n.showErrorNotification("订单保存失败");
                        return
                    }) : u.updateOutProcessOrder(n.currentOutprocessOrder).success(function() {
                        o.confirm("订单发送", "您确定要将订单发往技加工厂" + n.currentOutprocessOrder.supplyName + "？").then(function() {
                            u.sendOutProcessOrder(n.currentOutprocessOrder).success(function(t) {
                                t.result == "Success" ? (n.showNotification("发送成功！"), n.currentOutprocessOrder.networkOrderId = t.orderID) : n.showErrorNotification("发送失败！")
                            }).error(function() {
                                n.showErrorNotification("发送失败！")
                            })
                        })
                    }).error(function() {
                        n.showErrorNotification("订单保存失败");
                        return
                    })
                },
                w = function() {
                    u.getOutProcessStatus(n.currentOutprocessOrder.id).success(function(t) {
                        if (t.result == "Success") var r = i.open({
                            animation: !0,
                            backdrop: "static",
                            template: "<patient-outprocess-status-dialog><\/patient-outprocess-status-dialog>",
                            controller: "PatientOutprocessStatusDialogCtrl",
                            windowClass: "outprocessstatus-dialog",
                            size: "lg",
                            resolve: {
                                host: function() {
                                    return {
                                        orderProcedureList: t.orderProcedureList
                                    }
                                }
                            }
                        });
                        else n.showErrorNotification("无法获取状态！")
                    }).error(function() {
                        n.showErrorNotification("无法获取状态！")
                    })
                },
                b = function() {
                    o.confirm("注意", "编辑产品目录前将先关闭当前页面，是否继续？").then(function() {
                        e.switchState("outprocessCenter.dentureProducts", null)
                    })
                },
                f = function() {
                    var r, i;
                    if (n.factoryList && n.currentOutprocessOrder && ($("#supplyers").kendoDropDownList({
                            dataSource: n.factoryList,
                            placeholder: "请选择加工厂商",
                            dataTextField: "factoryName",
                            dataValueField: "factoryName",
                            select: function(t) {
                                var i = this.dataItem(t.item.index());
                                n.currentOutprocessOrder.supplyName = i.factoryName;
                                n.currentOutprocessOrder.factoryId = i.id;
                                n.currentOutprocessOrder.pickerPhone = i.salesManPhone;
                                n.$apply(function() {
                                    n.currentOutprocessOrder.pickerName = i.salesMan
                                })
                            }
                        }), r = t.find("#supplyers").data("kendoDropDownList"), r))
                        if (n.currentOutprocessOrder && n.currentOutprocessOrder.supplyName != "") {
                            for (i = 0; i < n.factoryList.length; ++i)
                                if (n.factoryList[i].factoryName == n.currentOutprocessOrder.supplyName) {
                                    n.currentOutprocessOrder.factoryId = n.factoryList[i].id;
                                    r.select(i);
                                    break
                                }
                        } else r.select(0), n.currentOutprocessOrder.supplyName = n.factoryList[0].factoryName, n.currentOutprocessOrder.pickerName = n.factoryList[0].salesMan, n.currentOutprocessOrder.factoryId = n.factoryList[0].id, n.currentOutprocessOrder.pickerPhone = n.factoryList[0].salesManPhone
                },
                k = function(t) {
                    n.itemType = t;
                    t == "技加工邻面板类型" ? n.boxTitle = "编辑邻面板" : t == "技加工卡环类型" ? n.boxTitle = "编辑卡环" : t == "技加工合支托类型" ? n.boxTitle = "编辑合支托" : t == "技加工附着体类型" ? n.boxTitle = "编辑附着体" : t == "色号" ? n.boxTitle = "编辑色号" : t == "技加工状态" && (n.boxTitle = "编辑技加工状态");
                    var i = s();
                    i.result.then(function() {
                        r.getItemTypes(t).success(function(i) {
                            t == "技加工邻面板类型" ? n.adjacentPanelList = i : t == "技加工卡环类型" ? n.snapRingList = i : t == "技加工合支托类型" ? n.occlusalRestList = i : t == "技加工附着体类型" ? n.attachmentList = i : t == "色号" ? n.colorCodeList = i : t == "技加工状态" && (n.statuses = i)
                        })
                    })
                },
                d = function() {
                    var r = i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<outprocess-factory-edit-dialog><\/outprocess-factory-edit-dialog>",
                        controller: "OutprocessFactoryEditCtrl",
                        size: "md",
                        resolve: {
                            host: function() {
                                return {
                                    factoryId: 0
                                }
                            }
                        }
                    });
                    r.result.then(function(i) {
                        if (n.factoryList) {
                            n.factoryList.push(i);
                            n.currentOutprocessOrder.factoryName = i.factoryName;
                            n.currentOutprocessOrder.factoryId = i.factoryId;
                            var r = t.find("#supplyers").data("kendoDropDownList");
                            r.value(i.factoryName)
                        } else n.factoryList = new kendo.data.ObservableArray(i)
                    })
                },
                g = function(t) {
                    if (!n.currentOutprocessOrder || !n.currentOutprocessOrder.id) {
                        log.info("订单不存在");
                        return
                    }
                    if (t && t.status == "已发送") {
                        n.showErrorNotification("已发送的图片无法删除！");
                        return
                    }
                    o.confirm("注意", "确定要删除此图片？").then(function() {
                        u.deleteOutProcessPicture(t.id).success(function() {
                            u.getOutProcessPictures(n.currentOutprocessOrder.id).success(function(t) {
                                n.showNotification("删除成功！");
                                n.pictureList = t
                            })
                        })
                    })
                },
                nt = function() {
                    if (!n.currentOutprocessOrder || !n.currentOutprocessOrder.factoryId) {
                        n.showErrorNotification("请先设置加工单位！");
                        return
                    }
                    var t = i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<outprocess-factory-edit-dialog><\/outprocess-factory-edit-dialog>",
                        controller: "OutprocessFactoryEditCtrl",
                        size: "md",
                        resolve: {
                            host: function() {
                                return {
                                    factoryId: n.currentOutprocessOrder.factoryId,
                                    editMode: "picker"
                                }
                            }
                        }
                    });
                    t.result.then(function(t) {
                        if (n.factoryList && n.factoryList.length > 0)
                            for (var i = 0; i < n.factoryList.length; ++i)
                                if (n.factoryList[i].factoryName == t.factoryName) {
                                    n.factoryList[i].salesMan = t.salesMan;
                                    n.factoryList[i].salesManPhone = t.salesManPhone;
                                    n.currentOutprocessOrder.pickerName = t.salesMan;
                                    n.currentOutprocessOrder.pickerPhone = t.salesManPhone;
                                    break
                                }
                    })
                },
                tt = function() {
                    return !n.currentOutprocessOrder || n.currentOutprocessOrder.id == 0 || n.currentOutprocessOrder.networkOrderId == "" || n.currentOutprocessOrder.networkOrderId == null ? !1 : !0
                },
                it = function() {
                    return n.currentOutprocessOrder && n.currentOutprocessOrder.networkOrderId != "" && n.currentOutprocessOrder.networkOrderId != null ? !1 : !0
                },
                rt = function() {
                    n.outProcessItemList && n.outProcessItemList != null && n.outProcessItemList.length && t.find("#dentalProductSearch").kendoItemNameCodeFilterComboBox({
                        filter: "contains",
                        placeholder: "请输入拼首码快速添加技加工产品",
                        dataTextField: "dentureProduct",
                        dataValueField: "id",
                        headerTemplate: '<div class="dropdown-select-head" style=" border-width: 0 0 1px 0;text-transform: uppercase;background-color:#f4f4f4;border-bottom: 1px solid #e3e3e3;" ><span style=" display: inline-block;width:200px;max-width:200px;margin-left:10px;padding:5px">项目名称<\/span><span style=" display: inline-block;width:80px;max-width:80px">拼首码<\/span><\/div>',
                        template: '<span class="dropdown-select-text" style=" display: inline-block;width:200px;max-width:200px;margin-left:10px;">#:data.dentureProduct #<\/span><span class="dropdown-select-text" style=" display: inline-block;width:80px;max-width:80px;">#: data.pinyin #<\/span>',
                        dataSource: n.outProcessItemList,
                        height: 370,
                        select: function(t) {
                            var i = this.dataItem(t.item.index());
                            n.selectProduct = i
                        },
                        change: function() {
                            var t, i;
                            if (n.selectProduct != null) {
                                if (this.value(""), n.currentOutprocessOrder.orderDetailList || (n.currentOutprocessOrder.orderDetailList = []), t = {}, t.id = 0, t.itemName = n.selectProduct.dentureProduct, t.material = n.selectProduct.material, t.repairType = n.selectProduct.repairType, t.processMethod = n.selectProduct.processMethod, t.stentMaterial = n.selectProduct.stentMaterial, t.baseMaterial = n.selectProduct.baseMaterial, i = _.find(n.currentOutprocessOrder.orderDetailList, function(n) {
                                        return n.itemName == t.itemName ? !0 : !1
                                    }), i) {
                                    n.showErrorNotification("不能重复添加相同产品!");
                                    return
                                }
                                n.$apply(n.currentOutprocessOrder.orderDetailList.push(t));
                                n.selectProduct = null
                            }
                        }
                    })
                },
                ut = function() {
                    n.currentOutprocessOrder && n.currentOutprocessOrder.orderType == "固定义齿" && n.currentOutprocessOrder.colorDetailList.push({
                        fdiToothCodesArray: [],
                        colorCode1: "",
                        colorCode2: "",
                        colorCode3: "",
                        clearLayer: !1,
                        enamel: !1,
                        fissure: !1
                    })
                },
                ft = function(t) {
                    n.currentOutprocessOrder && n.currentOutprocessOrder.colorDetailList && n.currentOutprocessOrder.colorDetailList.length >= t && n.currentOutprocessOrder.colorDetailList.splice(t, 1)
                },
                et = function() {
                    n.currentOutprocessOrder && n.currentOutprocessOrder.orderType == "活动义齿" && n.currentOutprocessOrder.designList.push({
                        fdiToothCodesArray: [],
                        occlusalRest: "",
                        adjacentPanel: "",
                        snapRing: "",
                        attachment: ""
                    })
                },
                ot = function(t) {
                    n.currentOutprocessOrder && n.currentOutprocessOrder.designList && n.currentOutprocessOrder.designList.length >= t && n.currentOutprocessOrder.designList.splice(t, 1)
                };
            (function() {
                n.isAllowSaveOrder = it;
                n.isAllowSendOrder = l;
                n.isAllowGetOrderStatus = v;
                n.isAllowSendPicture = tt;
                n.isAllowPrint = a;
                n.initFactory = f;
                n.openFullPicture = c;
                n.deletePicture = g;
                n.addColorDetail = ut;
                n.deleteColorDetail = ft;
                n.addDetail = et;
                n.deleteDetail = ot;
                n.editDesignType = k;
                n.$watch("currentOutprocessOrder", function() {
                    n.printTemplateId = n.currentOutprocessOrder && n.currentOutprocessOrder.orderType == "固定义齿" ? "gdyc" : "hdyc";
                    f()
                });
                n.$watch("factoryList", function() {
                    f()
                });
                n.$watch("statuses", function() {
                    h()
                });
                n.$watchCollection("outProcessItemList", function() {
                    rt()
                });
                n.sendOutProcessOrder = p;
                n.sendOrderPictures = y;
                n.getOutProcessStatus = w;
                n.editOutProcessItem = b;
                n.addSupplyers = d;
                n.editPickers = nt
            })()
        }
    }
}]);
patientModule.directive("patientOutprocessCatagoryDialog", ["$log", "$timeout", "dataDicSvc", "aresDialog", function(n, t, i) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/views/outprocess/patient-outprocess-catagory-dialog.html",
        link: function(n, r) {
            (function() {
                var r = i.systemsettingDic.data(),
                    t;
                for (n.productCatagoryList = [], t = 0; t < r.length; ++t) r[t].itemType == "义齿类别" && (r[t].itemName == "活动义齿" || r[t].itemName == "固定义齿") && n.productCatagoryList.push(r[t])
            })();
            t(function() {
                Ares.centerModal(r.closest(".modal-dialog"))
            }, 5)
        }
    }
}]);
patientModule.directive("patientOutprocessConnectView", ["$log", "$timeout", "$modal", "practiceSvc", "patientSvc", "appointmentSvc", "appNav", "aresDialog", function(n, t, i, r, u, f, e, o) {
    "use strict";
    return {
        templateUrl: "/app/patient/views/outprocess/patient-outprocess-connect-view.html",
        controller: "PatientOutprocessConnectCtrl",
        link: function(n, t) {
            var s = function() {
                    return i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<system-setting-item-edit><\/system-setting-item-edit>",
                        controller: "SystemSettingItemEditCtrl",
                        resolve: {
                            host: function() {
                                return {
                                    itemType: n.itemType
                                }
                            },
                            boxTitle: function() {
                                return n.boxTitle
                            }
                        }
                    })
                },
                h = function() {
                    var r, i;
                    if (n.statuses && n.statuses.length && ($("#orderStatus").kendoDropDownList({
                            dataSource: n.statuses,
                            placeholder: "请选择订单状态",
                            dataTextField: "itemName",
                            dataValueField: "id",
                            select: function(t) {
                                var i = this.dataItem(t.item.index());
                                n.currentOutprocessOrder.status = i.name
                            }
                        }), r = t.find("#orderStatus").data("kendoDropDownList"), r))
                        if (n.currentOutprocessOrder && n.currentOutprocessOrder.status) {
                            for (i = 0; i < n.statuses.length; ++i)
                                if (n.statuses[i].itemName == n.currentOutprocessOrder.status) {
                                    r.select(i);
                                    break
                                }
                        } else r.select(0)
                },
                c = function(n) {
                    var t = i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<ares-image-dialog><\/ares-image-dialog>",
                        controller: "AresImageDialogCtrl",
                        resolve: {
                            host: function() {
                                return {
                                    picture: n
                                }
                            }
                        }
                    })
                },
                l = function() {
                    return n.currentOutprocessOrder && n.currentOutprocessOrder.networkOrderId != "" && n.currentOutprocessOrder.networkOrderId != null ? !1 : !0
                },
                a = function() {
                    return n.currentOutprocessOrder && n.currentOutprocessOrder.id > 0 ? !0 : !1
                },
                v = function() {
                    return n.currentOutprocessOrder ? n.currentOutprocessOrder && n.currentOutprocessOrder.networkOrderId != "" && n.currentOutprocessOrder.networkOrderId != null ? !0 : n.currentOutprocessOrder && n.currentOutprocessOrder.id < 1 ? !1 : !1 : !1
                },
                y = function() {
                    if (!n.currentOutprocessOrder) return !1;
                    if (n.currentOutprocessOrder.id == 0) return n.showErrorNotification("请先保存订单后，再发送图片！"), !1;
                    if (!n.pictureList || n.pictureList.length == 0) return !1;
                    var t = [];
                    _.each(n.pictureList, function(n) {
                        n.status != "已发送" && t.push(n.id)
                    });
                    t.length > 0 && u.sendOutProcessPictureList(t).success(function(t) {
                        t == !0 ? n.showNotification("图片发送成功！") : n.showErrorNotification("图片发送失败！");
                        n.refreshPictureList()
                    })
                },
                p = function() {
                    var f = t.find("#doctor").data("kendoDropDownList"),
                        r, i, e, s;
                    if (n.currentOutprocessOrder.doctorName = f.text(), n.currentOutprocessOrder.doctorId = f.value(), r = t.find("#appoint").data("kendoDropDownList"), !r) {
                        n.showErrorNotification("没有关联的就诊时间，请先创建预约，再保存订单！");
                        return
                    }
                    if (n.currentOutprocessOrder.appointmentId = r.value(), !n.currentOutprocessOrder.appointmentId) {
                        n.showErrorNotification("没有关联的就诊时间，请先创建预约，再保存订单！");
                        return
                    }
                    for (i = 0; i < n.currentOutprocessOrder.orderDetailList.length; ++i) n.currentOutprocessOrder.orderDetailList[i].fDIToothCodes = n.currentOutprocessOrder.orderDetailList[i].fdiToothCodesArray.join(",");
                    n.currentOutprocessOrder.sendDate = moment(n.currentOutprocessOrder.sendDate).format("YYYY-MM-DD HH:mm");
                    n.currentOutprocessOrder.backDate = moment(n.currentOutprocessOrder.backDate).format("YYYY-MM-DD HH:mm");
                    e = t.find("#supplyers").data("kendoDropDownList");
                    n.currentOutprocessOrder.supplyName = e.text();
                    s = t.find("#orderStatus").data("kendoDropDownList");
                    n.currentOutprocessOrder.status = s.text();
                    n.currentOutprocessOrder.id == 0 ? u.createOutProcessOrder(n.currentOutprocessOrder).success(function(t) {
                        n.currentOutprocessOrder.id = t.id;
                        o.confirm("订单发送", "您确定要将订单发往技加工厂" + n.currentOutprocessOrder.supplyName + "？").then(function() {
                            u.sendOutProcessOrder(n.currentOutprocessOrder).success(function(t) {
                                t.result == "Success" ? (n.showNotification("发送成功！"), n.currentOutprocessOrder.networkOrderId = t.orderID) : n.showErrorNotification("发送失败！")
                            }).error(function() {
                                n.showErrorNotification("发送失败！")
                            })
                        })
                    }).error(function() {
                        n.showErrorNotification("订单保存失败");
                        return
                    }) : u.updateOutProcessOrder(n.currentOutprocessOrder).success(function() {
                        o.confirm("订单发送", "您确定要将订单发往技加工厂" + n.currentOutprocessOrder.supplyName + "？").then(function() {
                            u.sendOutProcessOrder(n.currentOutprocessOrder).success(function(t) {
                                t.result == "Success" ? (n.showNotification("发送成功！"), n.currentOutprocessOrder.networkOrderId = t.orderID) : n.showErrorNotification("发送失败！")
                            }).error(function() {
                                n.showErrorNotification("发送失败！")
                            })
                        })
                    }).error(function() {
                        n.showErrorNotification("订单保存失败");
                        return
                    })
                },
                w = function() {
                    u.getOutProcessStatus(n.currentOutprocessOrder.id).success(function(t) {
                        if (t.result == "Success") var r = i.open({
                            animation: !0,
                            backdrop: "static",
                            template: "<patient-outprocess-status-dialog><\/patient-outprocess-status-dialog>",
                            controller: "PatientOutprocessStatusDialogCtrl",
                            windowClass: "outprocessstatus-dialog",
                            size: "lg",
                            resolve: {
                                host: function() {
                                    return {
                                        orderProcedureList: t.orderProcedureList
                                    }
                                }
                            }
                        });
                        else n.showErrorNotification("无法获取状态！")
                    }).error(function() {
                        n.showErrorNotification("无法获取状态！")
                    })
                },
                b = function() {
                    o.confirm("注意", "编辑产品目录前将先关闭当前页面，是否继续？").then(function() {
                        e.switchState("outprocessCenter.dentureProducts", null)
                    })
                },
                f = function() {
                    var r, i;
                    if (n.factoryList && n.currentOutprocessOrder && ($("#supplyers").kendoDropDownList({
                            dataSource: n.factoryList,
                            placeholder: "请选择加工厂商",
                            dataTextField: "factoryName",
                            dataValueField: "factoryName",
                            select: function(t) {
                                var i = this.dataItem(t.item.index());
                                n.currentOutprocessOrder.supplyName = i.factoryName;
                                n.currentOutprocessOrder.factoryId = i.id;
                                n.currentOutprocessOrder.pickerPhone = i.salesManPhone;
                                n.$apply(function() {
                                    n.currentOutprocessOrder.pickerName = i.salesMan
                                })
                            }
                        }), r = t.find("#supplyers").data("kendoDropDownList"), r))
                        if (n.currentOutprocessOrder && n.currentOutprocessOrder.supplyName != "") {
                            for (i = 0; i < n.factoryList.length; ++i)
                                if (n.factoryList[i].factoryName == n.currentOutprocessOrder.supplyName) {
                                    n.currentOutprocessOrder.factoryId = n.factoryList[i].id;
                                    r.select(i);
                                    break
                                }
                        } else r.select(0), n.currentOutprocessOrder.supplyName = n.factoryList[0].factoryName, n.currentOutprocessOrder.pickerName = n.factoryList[0].salesMan, n.currentOutprocessOrder.factoryId = n.factoryList[0].id, n.currentOutprocessOrder.pickerPhone = n.factoryList[0].salesManPhone
                },
                k = function(t) {
                    n.itemType = t;
                    t == "技加工邻面板类型" ? n.boxTitle = "编辑邻面板" : t == "技加工卡环类型" ? n.boxTitle = "编辑卡环" : t == "技加工合支托类型" ? n.boxTitle = "编辑合支托" : t == "技加工附着体类型" ? n.boxTitle = "编辑附着体" : t == "色号" ? n.boxTitle = "编辑色号" : t == "技加工状态" && (n.boxTitle = "编辑技加工状态");
                    var i = s();
                    i.result.then(function() {
                        r.getItemTypes(t).success(function(i) {
                            t == "技加工邻面板类型" ? n.adjacentPanelList = i : t == "技加工卡环类型" ? n.snapRingList = i : t == "技加工合支托类型" ? n.occlusalRestList = i : t == "技加工附着体类型" ? n.attachmentList = i : t == "色号" ? n.colorCodeList = i : t == "技加工状态" && (n.statuses = i)
                        })
                    })
                },
                d = function() {
                    var r = i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<outprocess-factory-edit-dialog><\/outprocess-factory-edit-dialog>",
                        controller: "OutprocessFactoryEditCtrl",
                        size: "md",
                        resolve: {
                            host: function() {
                                return {
                                    factoryId: 0
                                }
                            }
                        }
                    });
                    r.result.then(function(i) {
                        if (n.factoryList) {
                            n.factoryList.push(i);
                            n.currentOutprocessOrder.pickerName = i.salesMan;
                            n.currentOutprocessOrder.factoryName = i.factoryName;
                            n.currentOutprocessOrder.factoryId = i.factoryId;
                            var r = t.find("#supplyers").data("kendoDropDownList");
                            r.value(i.factoryName)
                        } else n.factoryList = new kendo.data.ObservableArray(i)
                    })
                },
                g = function(t) {
                    if (!n.currentOutprocessOrder || !n.currentOutprocessOrder.id) {
                        log.info("订单不存在");
                        return
                    }
                    if (t && t.status == "已发送") {
                        n.showErrorNotification("已发送的图片无法删除！");
                        return
                    }
                    o.confirm("注意", "确定要删除此图片？").then(function() {
                        u.deleteOutProcessPicture(t.id).success(function() {
                            u.getOutProcessPictures(n.currentOutprocessOrder.id).success(function(t) {
                                n.showNotification("删除成功！");
                                n.pictureList = t
                            })
                        })
                    })
                },
                nt = function() {
                    if (!n.currentOutprocessOrder || !n.currentOutprocessOrder.factoryId) {
                        n.showErrorNotification("请先设置加工单位！");
                        return
                    }
                    var t = i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<outprocess-factory-edit-dialog><\/outprocess-factory-edit-dialog>",
                        controller: "OutprocessFactoryEditCtrl",
                        size: "md",
                        resolve: {
                            host: function() {
                                return {
                                    factoryId: n.currentOutprocessOrder.factoryId,
                                    editMode: "picker"
                                }
                            }
                        }
                    });
                    t.result.then(function(t) {
                        if (n.factoryList && n.factoryList.length > 0)
                            for (var i = 0; i < n.factoryList.length; ++i)
                                if (n.factoryList[i].factoryName == t.factoryName) {
                                    n.factoryList[i].salesMan = t.salesMan;
                                    n.factoryList[i].salesManPhone = t.salesManPhone;
                                    n.currentOutprocessOrder.pickerName = t.salesMan;
                                    n.currentOutprocessOrder.pickerPhone = t.salesManPhone;
                                    break
                                }
                    })
                },
                tt = function() {
                    return !n.currentOutprocessOrder || n.currentOutprocessOrder.id == 0 || n.currentOutprocessOrder.networkOrderId == "" || n.currentOutprocessOrder.networkOrderId == null ? !1 : !0
                },
                it = function() {
                    return n.currentOutprocessOrder && n.currentOutprocessOrder.networkOrderId != "" && n.currentOutprocessOrder.networkOrderId != null ? !1 : !0
                },
                rt = function() {
                    n.outProcessItemList && n.outProcessItemList != null && n.outProcessItemList.length && t.find("#dentalProductSearch").kendoItemNameCodeFilterComboBox({
                        filter: "contains",
                        placeholder: "请输入拼首码快速添加技加工产品",
                        dataTextField: "dentureProduct",
                        dataValueField: "id",
                        headerTemplate: '<div class="dropdown-select-head" style=" border-width: 0 0 1px 0;text-transform: uppercase;background-color:#f4f4f4;border-bottom: 1px solid #e3e3e3;" ><span style=" display: inline-block;width:200px;max-width:200px;margin-left:10px;padding:5px">项目名称<\/span><span style=" display: inline-block;width:80px;max-width:80px">拼首码<\/span><\/div>',
                        template: '<span class="dropdown-select-text" style=" display: inline-block;width:200px;max-width:200px;margin-left:10px;">#:data.dentureProduct #<\/span><span class="dropdown-select-text" style=" display: inline-block;width:80px;max-width:80px;">#: data.pinyin #<\/span>',
                        dataSource: n.outProcessItemList,
                        height: 370,
                        select: function(t) {
                            var i = this.dataItem(t.item.index());
                            n.selectProduct = i
                        },
                        change: function() {
                            var t, i;
                            if (n.selectProduct != null) {
                                if (this.value(""), n.currentOutprocessOrder.orderDetailList || (n.currentOutprocessOrder.orderDetailList = []), t = {}, t.id = 0, t.itemName = n.selectProduct.dentureProduct, t.material = n.selectProduct.material, t.repairType = n.selectProduct.repairType, t.processMethod = n.selectProduct.processMethod, t.stentMaterial = n.selectProduct.stentMaterial, t.baseMaterial = n.selectProduct.baseMaterial, i = _.find(n.currentOutprocessOrder.orderDetailList, function(n) {
                                        return n.itemName == t.itemName ? !0 : !1
                                    }), i) {
                                    n.showErrorNotification("不能重复添加相同产品!");
                                    return
                                }
                                n.$apply(n.currentOutprocessOrder.orderDetailList.push(t));
                                n.selectProduct = null
                            }
                        }
                    })
                },
                ut = function() {
                    n.currentOutprocessOrder && n.currentOutprocessOrder.orderType == "固定义齿" && n.currentOutprocessOrder.colorDetailList.push({
                        fdiToothCodesArray: [],
                        colorCode1: "",
                        colorCode2: "",
                        colorCode3: "",
                        clearLayer: !1,
                        enamel: !1,
                        fissure: !1
                    })
                },
                ft = function(t) {
                    n.currentOutprocessOrder && n.currentOutprocessOrder.colorDetailList && n.currentOutprocessOrder.colorDetailList.length >= t && n.currentOutprocessOrder.colorDetailList.splice(t, 1)
                },
                et = function() {
                    n.currentOutprocessOrder && n.currentOutprocessOrder.orderType == "活动义齿" && n.currentOutprocessOrder.designList.push({
                        fdiToothCodesArray: [],
                        occlusalRest: "",
                        adjacentPanel: "",
                        snapRing: "",
                        attachment: ""
                    })
                },
                ot = function(t) {
                    n.currentOutprocessOrder && n.currentOutprocessOrder.designList && n.currentOutprocessOrder.designList.length >= t && n.currentOutprocessOrder.designList.splice(t, 1)
                };
            (function() {
                n.isAllowSaveOrder = it;
                n.isAllowSendOrder = l;
                n.isAllowGetOrderStatus = v;
                n.isAllowSendPicture = tt;
                n.isAllowPrint = a;
                n.initFactory = f;
                n.openFullPicture = c;
                n.deletePicture = g;
                n.addColorDetail = ut;
                n.deleteColorDetail = ft;
                n.addDetail = et;
                n.deleteDetail = ot;
                n.editDesignType = k;
                n.$watch("currentOutprocessOrder", function() {
                    n.printTemplateId = n.currentOutprocessOrder && n.currentOutprocessOrder.orderType == "固定义齿" ? "gdyc" : "hdyc";
                    f()
                });
                n.$watch("factoryList", function() {
                    f()
                });
                n.$watch("statuses", function() {
                    h()
                });
                n.$watchCollection("outProcessItemList", function() {
                    rt()
                });
                n.sendOutProcessOrder = p;
                n.sendOrderPictures = y;
                n.getOutProcessStatus = w;
                n.editOutProcessItem = b;
                n.addSupplyers = d;
                n.editPickers = nt
            })()
        }
    }
}]);
patientModule.directive("patientOutprocessEditView", ["$log", "$timeout", "$modal", "practiceSvc", "appointmentSvc", function(n, t, i, r) {
    "use strict";
    return {
        templateUrl: "/app/patient/views/outprocess/patient-outprocess-edit-view.html",
        controller: "PatientOutprocessEditCtrl",
        link: function(n, t) {
            var u = function() {
                    return i.open({
                        animation: !0,
                        backdrop: "static",
                        template: "<system-setting-item-edit><\/system-setting-item-edit>",
                        controller: "SystemSettingItemEditCtrl",
                        resolve: {
                            host: function() {
                                return {
                                    itemType: n.itemType
                                }
                            },
                            boxTitle: function() {
                                return n.boxTitle
                            }
                        }
                    })
                },
                o = function() {
                    n.itemType = "技加工状态";
                    n.boxTitle = "编辑订单状态";
                    var t = u();
                    t.result.then(function() {
                        r.getOutProcessStatus().success(function(t) {
                            n.statuses = t;
                            n.initStatus()
                        })
                    })
                },
                s = function() {
                    n.itemType = "技加工项目";
                    n.boxTitle = "编辑技加工项目";
                    var t = u();
                    t.result.then(function() {
                        n.reloadSystemSettingItem()
                    })
                },
                h = function() {
                    n.itemType = "色号";
                    n.boxTitle = "编辑色号";
                    var t = u();
                    t.result.then(function() {
                        n.reloadSystemSettingItem()
                    })
                },
                c = function() {
                    n.itemType = "技加工单位";
                    n.boxTitle = "编辑技加工单位";
                    var t = u();
                    t.result.then(function() {
                        r.getOutProcesser().success(function(t) {
                            n.supplyers = t;
                            n.initSuppliers()
                        })
                    })
                },
                l = function() {
                    n.itemType = "取件人";
                    n.boxTitle = "编辑取件人";
                    var t = u();
                    t.result.then(function() {
                        r.getOutProcessDelivery().success(function(t) {
                            n.pickers = t;
                            n.initPickers()
                        })
                    })
                },
                f = function(i, r) {
                    if (n.outProcessItemList) {
                        t.find("#processItem" + i).kendoMultiFilterAutoComplete({
                            dataTextField: "itemName",
                            dataValueField: "itemName",
                            dataSource: n.outProcessItemList,
                            template: '<span class="k-state-default">#: data.itemName #<\/span>',
                            separator: ","
                        });
                        var u = r.split(","),
                            f = t.find("#processItem" + i).data("kendoAresMultiSelect");
                        f ? r != "" && (f.aresRefreshDataSource(u), f.value(u)) : t.find("#processItem" + i).kendoAresMultiSelect({
                            dataTextField: "itemName",
                            dataValueField: "itemName",
                            dataSource: n.outProcessItemList,
                            value: u,
                            separator: ","
                        })
                    }
                },
                a = function(n) {
                    var i = t.find(n).data("kendoAresMultiSelect");
                    return i.value()
                },
                e = function(i, r) {
                    if (n.colorCodeList) {
                        t.find("#colorCode" + i).kendoMultiFilterAutoComplete({
                            dataTextField: "itemName",
                            dataValueField: "itemName",
                            dataSource: n.colorCodeList,
                            template: '<span class="k-state-default">#: data.itemName #<\/span>',
                            separator: ","
                        });
                        var u = r.split(","),
                            f = t.find("#colorCode" + i).data("kendoAresMultiSelect");
                        f ? r != "" && (f.aresRefreshDataSource(u), f.value(u)) : t.find("#colorCode" + i).kendoAresMultiSelect({
                            dataTextField: "itemName",
                            dataValueField: "itemName",
                            dataSource: n.colorCodeList,
                            value: u,
                            separator: ","
                        })
                    }
                };
            (function() {
                n.editOrderType = o;
                n.editOutProcessItem = s;
                n.editColorCode = h;
                n.editSupplyers = c;
                n.editPickers = l;
                n.initProcessItemDropDown = f;
                n.initColorCodeDropDown = e;
                n.getDropDownValue = a;
                n.$watch("isLoadOK", function() {
                    n.isLoadOK && n.currentOutprocessOrder && n.currentOutprocessOrder.orderDetailList && angular.forEach(n.currentOutprocessOrder.orderDetailList, function(n, t) {
                        f(t, n.itemName);
                        e(t, n.colorCode)
                    })
                });
                n.$watch("currentOutprocessOrder.orderDetailList", function(t, i) {
                    n.currentOutprocessOrder && n.currentOutprocessOrder.orderDetailList && t && i && t.length == i.length && angular.forEach(t, function(r, u) {
                        var f = t[u].fdiToothCodesArray.join(",") == i[u].fdiToothCodesArray.join(",");
                        f || (n.currentOutprocessOrder.orderDetailList[u].count = n.currentOutprocessOrder.orderDetailList[u].fdiToothCodesArray.length)
                    })
                }, !0)
            })()
        }
    }
}]);
patientModule.directive("patientOutprocessPictureUpload", ["$log", "$timeout", "$state", function() {
    "use strict";
    return {
        restrict: "A",
        scope: {
            add: "&",
            send: "&",
            start: "&",
            stop: "&",
            fail: "&",
            destroy: "&",
            done: "&",
            uploadprogress: "&"
        },
        link: function(n, t) {
            function i(n, t) {
                var i = {
                    dataType: "json",
                    type: "POST",
                    sequentialUploads: !0,
                    autoUpload: !0,
                    multipart: !1
                };
                n.add && (i.add = function(t, i) {
                    n.$apply(function() {
                        n.add({
                            e: t,
                            data: i
                        })
                    })
                });
                n.fail && (i.fail = function(t, i) {
                    n.$apply(function() {
                        n.fail({
                            e: t,
                            data: i
                        })
                    })
                });
                n.done && (i.done = function(t, i) {
                    n.$apply(function() {
                        n.done({
                            e: t,
                            data: i
                        })
                    })
                });
                n.uploadprogress && (i.progress = function(t, i) {
                    n.$apply(function() {
                        n.uploadprogress({
                            e: t,
                            data: i
                        })
                    })
                });
                t.fileupload(i)
            }
            var r = function() {
                    $("#uploadPicture").on("click", u)
                },
                u = function() {
                    if (!n.$parent.currentOutprocessOrder) return !1;
                    if (n.$parent.currentOutprocessOrder.id == 0) return n.$parent.showErrorNotification("请先保存订单后，再上传图片！"), !1;
                    $("#pictureUploadPanel").click()
                };
            (function() {
                r()
            })(i(n, t))
        }
    }
}]);
patientModule.directive("patientOutprocessStatusDialog", ["$log", "$timeout", "dataDicSvc", "patientSvc", "aresDialog", function(n, t) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/views/outprocess/patient-outprocess-status-dialog.html",
        link: function(n, i) {
            var r = !0,
                u = function() {
                    var t, u, f;
                    n.orderProcedureList && (t = $(i).find("#statusGrid"), r = !1, t.kendoGrid({
                        dataSource: {
                            data: n.orderProcedureList,
                            schema: {
                                model: {
                                    id: "id",
                                    fields: {
                                        oTime: {
                                            type: "date"
                                        },
                                        dName: {
                                            type: "string"
                                        },
                                        eName: {
                                            type: "string"
                                        },
                                        dProcedure: {
                                            type: "string"
                                        },
                                        remark: {
                                            type: "string"
                                        },
                                        isFinished: {
                                            type: "string"
                                        },
                                        isRedo: {
                                            type: "string"
                                        }
                                    }
                                }
                            }
                        },
                        scrollable: !1,
                        sortable: !0,
                        selectable: "single",
                        columns: [{
                            field: "oTime",
                            title: "业务时间",
                            width: "120px",
                            template: "#: moment(oTime).format('YYYY-MM-DD HH:mm:ss') #"
                        }, {
                            field: "dName",
                            title: "部门",
                            width: "70px"
                        }, {
                            field: "eName",
                            title: "操作员",
                            width: "70px"
                        }, {
                            field: "dProcedure",
                            title: "步骤",
                            width: "80px"
                        }, {
                            field: "remark ",
                            title: "说明",
                            width: "100px"
                        }, {
                            field: "isFinished",
                            title: "是否完成",
                            width: "60px",
                            template: "#: isFinished==1?'是':'否' # "
                        }]
                    }), u = t.data("kendoGrid"), f = [{
                        field: "sTime",
                        dir: "desc"
                    }], u.dataSource.sort(f))
                };
            (function() {
                n.$watch("orderProcedureList", function() {
                    if (r) u();
                    else {
                        var f = $(i).find("#statusGrid"),
                            t = patientListElement.data("kendoGrid");
                        t.dataSource.data(n.orderProcedureList)
                    }
                })
            })();
            t(function() {
                Ares.centerModal(i.closest(".modal-dialog"))
            }, 5)
        }
    }
}]);
patientModule.directive("patientOutprocessTableView", ["$log", "$timeout", "$window", "permissionProvider", function(n, t, i, r) {
    "use strict";
    return {
        templateUrl: "/app/patient/views/outprocess/patient-outprocess-table-view.html",
        controller: "PatientOutprocessCtrl",
        link: function(n, t) {
            var e = Ares.kendoGridUtil(i, n),
                u = !1;
            n.allowed = r.isAllowed("patientOutProcess.viewPrice");
            var o = function() {
                    if (n.outProcessOrders) {
                        u = !0;
                        n.gridColumns = [];
                        n.$root.isRegularChain && n.gridColumns.push({
                            field: "officeName",
                            title: "诊所",
                            width: "100px"
                        });
                        n.gridColumns.push({
                            field: "supplyName",
                            title: "加工单位",
                            width: "100px"
                        }, {
                            hidden: !n.allowed,
                            field: "customerPrice",
                            title: "患者收费",
                            width: "40px"
                        }, {
                            hidden: !n.allowed,
                            field: "factoryPrice",
                            title: "加工费",
                            width: "40px"
                        }, {
                            field: "sendDate",
                            title: "送件时间",
                            width: "80px"
                        }, {
                            field: "backDate",
                            title: "收件时间",
                            width: "80px"
                        }, {
                            field: "status",
                            title: "状态",
                            width: "40px"
                        }, {
                            field: "notes",
                            title: "备注",
                            width: "40px"
                        }, {
                            template: e.commandTemplate,
                            title: "",
                            width: "60px"
                        });
                        var i = t.find("#outprocessList");
                        i.kendoGrid({
                            dataSource: {
                                data: n.outProcessOrders
                            },
                            scrollable: !1,
                            sortable: !0,
                            selectable: "single",
                            model: {
                                id: "id"
                            },
                            columns: n.gridColumns
                        })
                    }
                },
                s = function() {
                    var n = [];
                    return r.isAllowed("patientOutProcess.update") && n.push({
                        text: "编辑",
                        action: "goToOutprocess",
                        icon: "glyphicon-edit"
                    }), r.isAllowed("patientOutProcess.delete") && n.push({
                        text: "删除",
                        action: "deleteOutProcessOrder",
                        icon: "glyphicon-trash"
                    }), n.push({
                        text: "打印",
                        action: "printOutProcessOrder",
                        icon: "glyphicon glyphicon-print"
                    }), n.push({
                        text: "查看日志",
                        action: "viewOutProcessOrderLog",
                        icon: "iconfont icon-rizhi"
                    }), n
                },
                f = function(t) {
                    return _.find(n.outProcessOrders, function(n) {
                        return n.id == t
                    })
                },
                h = function(t, i, r) {
                    n.$apply(function() {
                        var t = f(r);
                        switch (i) {
                            case "goToOutprocess":
                                n.editOutProcessOrder(t);
                                break;
                            case "deleteOutProcessOrder":
                                n.deleteOutProcessOrder(t);
                                break;
                            case "printOutProcessOrder":
                                n.printOutProcessOrder(t);
                                break;
                            case "viewOutProcessOrderLog":
                                n.viewOutProcessOrderLog(t)
                        }
                    })
                },
                c = function() {
                    if (n.outProcessOrders) {
                        var t = $("#outprocessList"),
                            i = t.data("kendoGrid");
                        i.dataSource.data(n.outProcessOrders)
                    }
                };
            (function() {
                n.commands = s();
                n.onCommandClick = h;
                n.findOrder = f;
                n.$watch("outProcessOrders", function() {
                    u ? c() : o()
                })
            })()
        }
    }
}]);
patientModule.directive("patientOutprocessView", ["$log", "$timeout", "$state", "$modal", "appNav", "enums", "eventAggregator", "practiceSvc", function(n, t, i, r, u, f, e, o) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/views/outprocess/patient-outprocess-view.html",
        controller: "PatientOutprocessCtrl",
        scope: {
            patientId: "@"
        },
        link: function(n) {
            var t = function(n) {
                    u.switchState(n, f)
                },
                i = function() {
                    var t = !1;
                    o.getSystemConfigByName("AllowConnectFactory").success(function(i) {
                        if (i.configValue == "true" && (t = !0), t == !1) n.switchState("patientOutProcess.createRecord");
                        else {
                            var f = r.open({
                                animation: !0,
                                backdrop: "static",
                                template: "<patient-outprocess-catagory-dialog><\/patient-outprocess-catagory-dialog>",
                                controller: "PatientOutprocessCatagoryDialogCtrl",
                                size: "sm"
                            });
                            f.result.then(function(t) {
                                t && (t == "固定义齿" ? u.switchState("patientOutProcess.createFixedDentureRecord", {
                                    patientId: n.patientId,
                                    orderId: 0,
                                    status: 0,
                                    cata: t
                                }) : u.switchState("patientOutProcess.createConnectRecord", {
                                    patientId: n.patientId,
                                    orderId: 0,
                                    status: 0,
                                    cata: t
                                }))
                            })
                        }
                    })
                },
                f = function() {
                    var t = n.patientId;
                    return {
                        patientId: t
                    }
                };
            (function() {
                n.switchState = t;
                n.createNewOrder = i
            })()
        }
    }
}]);
patientModule.directive("patientOutprocessPrintTemplate", ["$log", "$timeout", "pictureSvc", "practiceSvc", "$filter", "$sce", "toothUtil", function() {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/views/outprocess/outprocess-print/patient-outprocess-print-template.html",
        link: function() {
            (function() {})()
        }
    }
}]);
patientModule.directive("allPatientListView", ["$log", "$timeout", "$filter", "$window", "$state", "appNav", "enums", "permissionProvider", function(n, t, i, r, u, f, e, o) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "AllPatientCtrl",
        templateUrl: "/app/patient/views/patient-list/all-patient-list-view.html",
        scope: {
            officeId: "="
        },
        link: function(n, i) {
            var h = Ares.kendoGridUtil(r, n),
                e = null,
                l = [{
                    field: "name",
                    title: "姓名",
                    width: "60px",
                    template: h.patientNameTemplate
                }, {
                    field: "privateId",
                    title: "病历号",
                    width: "60px"
                }, {
                    field: "brithStr",
                    title: "生日",
                    width: "100px"
                }, {
                    field: "mobile",
                    title: "手机",
                    width: "80px"
                }, {
                    field: "doctorName",
                    title: "主治医生",
                    width: "40px"
                }, {
                    field: "recordCreatedStr",
                    title: "创建日期",
                    width: "60px"
                }, {
                    field: "notes",
                    title: "备注",
                    width: "150px"
                }, {
                    template: h.commandTemplate,
                    title: "",
                    width: "110px"
                }],
                a, s;
            n.$root.isRegularChain && l.splice(1, 0, {
                field: "officeName",
                title: "所属诊所",
                width: "60px"
            });
            a = function() {
                var t, r;
                n.searchResult && (t = $(i).find("#patientList"), t.kendoGrid({
                    dataSource: {
                        data: n.searchResult.items
                    },
                    scrollable: !1,
                    sortable: !0,
                    selectable: "single",
                    model: {
                        id: "id"
                    },
                    columns: l
                }), e = t.data("kendoGrid"), r = [{
                    field: "recordCreatedStr",
                    dir: "desc"
                }], e.dataSource.sort(r))
            };
            s = [{
                text: "预约",
                action: "newAppt",
                icon: "glyphicon-plus-sign"
            }, ];
            o.isSmsAllowed && s.push({
                text: "发短信",
                action: "sendMessage",
                icon: "glyphicon-comment"
            });
            o.isPatientDeleteAllowed && s.push({
                text: "删除",
                action: "deletePatient",
                icon: "glyphicon-trash"
            });
            var y = function() {
                    var n = u.params.patientId;
                    n && t(function() {
                        v(n)
                    }, 500)
                },
                p = function(t, i, r) {
                    n.$apply(function() {
                        var t = w(r);
                        switch (i) {
                            case "goToPatient":
                                f.goToPatient(t.id);
                                break;
                            case "sendMessage":
                                n.sendMessage(r, -1);
                                break;
                            case "deletePatient":
                                n.deletePatient(t);
                                break;
                            case "newAppt":
                                n.createFollowUpApptByPatientId(r)
                        }
                    })
                },
                w = function(t) {
                    var i;
                    return n.selectPateint ? _.find(n.getPatient.items, function(n) {
                        return n.id == t
                    }) : _.find(n.searchResult.items, function(n) {
                        return n.id == t
                    })
                },
                c = function() {
                    var t = $("#patientList"),
                        i = t.data("kendoGrid");
                    i.dataSource.data(n.searchResult.items)
                },
                v = function(n) {
                    var t = $(i).find("#patientList"),
                        r = t.data("kendoGrid"),
                        f = r.dataSource,
                        e = f.get(n),
                        u = t.find("tbody>tr[data-uid=" + e.uid + "]");
                    u && r.select(u)
                },
                b = function(n) {
                    c();
                    v(n.id)
                },
                k = function() {
                    return e != null
                };
            (function() {
                n.commands = s;
                n.onCommandClick = p;
                n.refreshPatient = b;
                n.refreshPatientGrid = c;
                n.isInitialized = k;
                n.$watch("searchResult.items", function() {
                    e ? c() : (a(), y())
                });
                n.$on("$destroy", function() {
                    h.dispose()
                })
            })()
        }
    }
}]);
patientModule.directive("archivedPatientListView", ["$log", "$timeout", "$window", "$state", "appNav", "permissionProvider", "gridOptionUtil", function(n, t, i, r, u, f, e) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "ArchivedPatientListCtrl",
        // templateUrl: "/app/patient/views/patient-list/archived-patient-list-view.html",
        scope: {
            officeId: "="
        },
        link: function(n, o) {
            var c = Ares.kendoGridUtil(i, n),
                s = null,
                a = [{
                    field: "name",
                    title: "姓名",
                    width: "60px",
                    template: c.patientNameTemplate,
                    attributes: e.noPadding
                }, {
                    field: "privateId",
                    title: "病历号",
                    width: "60px",
                    attributes: e.noPadding
                }, {
                    field: "brithStr",
                    title: "生日",
                    width: "90px",
                    attributes: e.noPadding
                }, {
                    field: "mobile",
                    title: "手机",
                    width: "70px",
                    attributes: e.noPadding
                }, {
                    field: "sourceType",
                    title: "患者来源 ",
                    width: "60px",
                    attributes: e.noPadding
                }, {
                    field: "recordCreatedStr",
                    title: "创建日期",
                    width: "60px",
                    attributes: e.noPadding
                }, {
                    field: "notes",
                    title: "备注",
                    width: "80px",
                    attributes: e.noPadding
                }, {
                    field: "archivedTimeStr",
                    title: "归档日期",
                    width: "100px",
                    attributes: e.noPadding
                }, {
                    field: "archivedUserName",
                    title: "归档人",
                    width: "60px",
                    attributes: e.noPadding
                }, {
                    template: c.commandTemplate,
                    title: "",
                    width: "80px"
                }],
                v, h;
            n.$root.isRegularChain && a.splice(1, 0, {
                field: "officeName",
                title: "所属诊所",
                width: "60px",
                attributes: e.noPadding
            });
            v = function() {
                var t, i;
                n.searchResult && (t = $(o).find("#patientList"), t.kendoGrid({
                    dataSource: {
                        data: n.searchResult.items
                    },
                    scrollable: !1,
                    sortable: !0,
                    selectable: "single",
                    model: {
                        id: "id"
                    },
                    columns: a
                }), s = t.data("kendoGrid"), i = [{
                    field: "recordCreatedStr",
                    dir: "desc"
                }], s.dataSource.sort(i))
            };
            h = [];
            f.isPatientDeleteAllowed && (h.push({
                text: "解除归档",
                action: "undoArchive",
                icon: "icon-key"
            }), h.push({
                text: "删除患者",
                action: "deletePatient",
                icon: "glyphicon-trash"
            }));
            var p = function() {
                    var n = r.params.patientId;
                    n && t(function() {
                        y(n)
                    }, 500)
                },
                w = function(t, i, r) {
                    n.$apply(function() {
                        var t = b(r);
                        switch (i) {
                            case "goToPatient":
                                u.goToPatient(t.id);
                                break;
                            case "undoArchive":
                                n.undoArchive(t);
                                break;
                            case "deletePatient":
                                n.deletePatient(t)
                        }
                    })
                },
                b = function(t) {
                    var i;
                    return n.selectPateint ? _.find(n.getPatient.items, function(n) {
                        return n.id == t
                    }) : _.find(n.searchResult.items, function(n) {
                        return n.id == t
                    })
                },
                l = function() {
                    var t = $("#patientList"),
                        i = t.data("kendoGrid");
                    i.dataSource.data(n.searchResult.items)
                },
                y = function(n) {
                    var t = $(o).find("#patientList"),
                        i = t.data("kendoGrid"),
                        u = i.dataSource,
                        f = u.get(n),
                        r = t.find("tbody>tr[data-uid=" + f.uid + "]");
                    r && i.select(r)
                },
                k = function(n) {
                    l();
                    y(n.id)
                },
                d = function() {
                    return s != null
                };
            (function() {
                n.commands = h;
                n.onCommandClick = w;
                n.refreshPatient = k;
                n.refreshPatientGrid = l;
                n.isInitialized = d;
                n.$watch("searchResult.items", function() {
                    s ? l() : (v(), p())
                });
                n.$on("$destroy", function() {
                    c.dispose()
                })
            })()
        }
    }
}]);
patientModule.directive("duplicatedPatientListView", ["$log", "$timeout", "$filter", "$window", "$state", "appNav", "enums", "permissionProvider", "gridOptionUtil", function(n, t, i, r, u, f, e, o, s) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "DuplicatedPatientCtrl",
        templateUrl: "/app/patient/views/patient-list/duplicated-patient-list-view.html",
        link: function(n, i) {
            var u = Ares.kendoGridUtil(r, n),
                e, h = [];
            o.isPatientDeleteAllowed && h.push({
                text: "删除",
                action: "deletePatient",
                icon: "glyphicon-trash"
            });
            var c = function() {
                    var f = $(window).height() - 155,
                        t = [{
                            field: "name",
                            title: "姓名",
                            width: "120px",
                            attributes: s.noPadding,
                            template: u.patientNameTemplate
                        }, {
                            field: "privateId",
                            title: "病历号",
                            width: "60px"
                        }, {
                            field: "brithStr",
                            title: "生日",
                            width: "100px"
                        }, {
                            field: "mobile",
                            title: "手机",
                            width: "80px"
                        }, {
                            field: "doctorName",
                            title: "主治医生",
                            width: "80px"
                        }, {
                            field: "recordCreatedStr",
                            title: "创建日期",
                            width: "100px"
                        }, {
                            field: "notes",
                            title: "备注",
                            width: "150px"
                        }, ],
                        r;
                    n.$root.isRegularChain && t.splice(1, 0, {
                        field: "officeName",
                        title: "所属诊所",
                        width: "60px"
                    });
                    h.length > 0 && t.push({
                        template: u.commandTemplate,
                        title: "",
                        width: "60px"
                    });
                    r = i.find("#patientList");
                    e = r.kendoGrid({
                        dataSource: s.dataSource(l),
                        scrollable: !0,
                        sortable: !0,
                        selectable: "single",
                        model: {
                            id: "id"
                        },
                        columns: t,
                        height: f,
                        pageable: s.pageable
                    }).data("kendoGrid")
                },
                l = function(t) {
                    n.search(t.data.page, t.data.pageSize).then(function(n) {
                        t.success(n)
                    })
                },
                a = function(i, r, u) {
                    t(function() {
                        var t = v(u);
                        switch (r) {
                            case "goToPatient":
                                f.goToPatient(t.id);
                                break;
                            case "deletePatient":
                                n.deletePatient(t)
                        }
                    })
                },
                v = function(t) {
                    return _.find(n.searchResult.items, function(n) {
                        return n.id == t
                    })
                },
                y = function() {
                    if (e) {
                        var n = i.find(".k-textbox").val() || 1;
                        e.dataSource.page(n)
                    } else c()
                };
            (function() {
                n.commands = h;
                n.onCommandClick = a;
                n.refreshPatientGrid = y;
                c();
                n.$on("$destroy", function() {
                    u.dispose()
                })
            })()
        }
    }
}]);
patientModule.directive("patientListHomeView", ["$log", "$timeout", "$state", "$location", "appNav", "permissionProvider", "moduleOptionProvider", function(n, t, i, r, u) {
    "use strict";
    return {
        restrict: "E",
        templateUrl: "/app/patient/views/patient-list/patient-list-home-view.html",
        link: function(n) {
            var t = function() {
                var t = [],
                    i = localStorage.getItem("currentSearch"),
                    r = i ? i : "old";
                t = r == "new" ? [new u.TabItem("patientCenter.patientList.patientAdvanceSearch", "患者查询", "glyphicon glyphicon-search", "patientCenter.allPatients"), new u.TabItem("patientCenter.patientList.duplicated", "重复患者", "icon-users", "patientCenter.duplicatedPatient"), new u.TabItem("patientCenter.patientList.archived", "归档患者", "icon-users", "patientCenter.archivedPatient"), ] : [new u.TabItem("patientCenter.patientList.search", "患者查询", "glyphicon glyphicon-search", "patientCenter.allPatients"), new u.TabItem("patientCenter.patientList.duplicated", "重复患者", "icon-users", "patientCenter.duplicatedPatient"), new u.TabItem("patientCenter.patientList.archived", "归档患者", "icon-users", "patientCenter.archivedPatient"), ];
                n.states = t
            };
            (function() {
                t()
            })()
        }
    }
}]);
patientModule.directive("searchPatientView", ["$log", "$timeout", "$window", "appNav", "aresDialog", "aresNotification", "permissionProvider", "practiceSvc", function(n, t, i, r, u, f, e, o) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        controller: "SearchPatientCtrl",
        templateUrl: "/app/patient/views/patient-list/search-patient-view.html",
        scope: {
            officeId: "="
        },
        link: function(n, t) {
            var h = Ares.kendoGridUtil(i, n),
                s = null,
                y = function() {
                    var t = [],
                        i;
                    return n.searchConfig && (i = _.sortBy(n.searchConfig.searchResultFields, "showOrder"), angular.forEach(i, function(n) {
                        t.splice(n.showOrder, 0, p(n.code))
                    })), t.push({
                        template: h.commandTemplate,
                        title: "",
                        width: "140px"
                    }), t
                },
                p = function(n) {
                    var t = {};
                    switch (n) {
                        case "Name":
                            t = {
                                field: "name",
                                title: "患者姓名",
                                template: h.patientNameTemplate
                            };
                            break;
                        case "PrivateId":
                            t = {
                                field: "privateId",
                                title: "病历号",
                                filterable: {
                                    cell: {
                                        showOperators: !1
                                    }
                                },
                                width: 150
                            };
                            break;
                        case "PatientType":
                            t = {
                                field: "patientType",
                                title: "患者类型"
                            };
                            break;
                        case "Sex":
                            t = {
                                field: "sexStr",
                                title: "性别"
                            };
                            break;
                        case "Age":
                            t = {
                                field: "ageStr",
                                title: "年龄"
                            };
                            break;
                        case "Birth":
                            t = {
                                field: "brithStr",
                                title: "生日"
                            };
                            break;
                        case "Mobile":
                            t = {
                                field: "mobile",
                                title: "手机号码"
                            };
                            break;
                        case "PhoneNumber":
                            t = {
                                field: "phoneNumber",
                                title: "电话"
                            };
                            break;
                        case "SourceType":
                            t = {
                                field: "sourceType",
                                title: "患者来源"
                            };
                            break;
                        case "FirstVisit":
                            t = {
                                field: "firstVisitStr",
                                title: "初诊日期"
                            };
                            break;
                        case "DoctorName":
                            t = {
                                field: "doctorName",
                                title: "初诊医生"
                            };
                            break;
                        case "LastVisit":
                            t = {
                                field: "lastVisitStr",
                                title: "上次就诊时间"
                            };
                            break;
                        case "LastDoctorName":
                            t = {
                                field: "lastDoctorName",
                                title: "上次就诊医生"
                            };
                            break;
                        case "MembershipType":
                            t = {
                                field: "membershipType",
                                title: "会员类型"
                            };
                            break;
                        case "RecordCreatedTime":
                            t = {
                                field: "recordCreatedStr",
                                title: "创建时间"
                            };
                            break;
                        case "RecordCreatedUserName":
                            t = {
                                field: "recordCreatedUserName",
                                title: "创建人"
                            };
                            break;
                        case "Notes":
                            t = {
                                field: "notes",
                                title: "备注"
                            }
                    }
                    return t
                },
                w = function() {
                    var i = $(t).find("#patientList");
                    s = i.kendoGrid({
                        dataSource: {
                            data: n.searchData.items
                        },
                        scrollable: !1,
                        sortable: !0,
                        selectable: "single",
                        model: {
                            id: "id"
                        },
                        columns: y()
                    });
                    s = i.data("kendoGrid")
                },
                a = function() {
                    s && n.pageChage ? s.dataSource.data(n.searchData.items) : w()
                },
                c = [{
                    text: "创建预约",
                    action: "newAppt",
                    icon: "glyphicon-plus-sign"
                }, ];
            e.isSmsAllowed && c.push({
                text: "发短信",
                action: "sendMessage",
                icon: "glyphicon-comment"
            });
            e.isPatientDeleteAllowed && c.push({
                text: "删除",
                action: "deletePatient",
                icon: "glyphicon-trash"
            });
            var b = function(t, i, u) {
                    n.$apply(function() {
                        var t = k(u);
                        switch (i) {
                            case "goToPatient":
                                r.goToPatient(t.id);
                                break;
                            case "sendMessage":
                                n.sendMessage(u, -1);
                                break;
                            case "deletePatient":
                                n.deletePatient(t);
                                break;
                            case "newAppt":
                                n.createFollowUpApptByPatientId(u)
                        }
                    })
                },
                k = function(t) {
                    return _.find(n.searchData.items, function(n) {
                        return n.id == t
                    })
                },
                l = function(i) {
                    t.find("#searchDropDown").kendoDropDownList({
                        dataTextField: "name",
                        dataValueField: "id",
                        template: '<div class="templateDiv"><table style="width:100%;"><tr><td style="width:150px;"><span>#: data.name #<\/span><\/td><td style="width:25px;"><button type="button" class="btn btn-default btn-xs delBtn" isDisposable="#: data.isDisposable #" isDefault="#: data.isDefault #" searchId="#: data.id #" title="删除"> <span class="glyphicon glyphicon-trash" aria-hidden="true"><\/span><\/button><\/td><td style="width:25px;"><button type="button" class="btn btn-default btn-xs editBtn" isDisposable="#: data.isDisposable #"  searchId="#: data.id #" title="编辑"> <span class="glyphicon glyphicon-pencil" aria-hidden="true"><\/span><\/button><\/td><td><img width="20" height="20" style="cursor:pointer;" code="#: data.name #" isDisposable="#: data.isDisposable #" isPreferred="#: data.isPreferred #" searchId="#: data.id #" src="" title="设为默认搜索条件" /><\/td><\/tr><\/table><\/div>',
                        dataSource: n.searchConfigs,
                        dataBound: d,
                        height: 400
                    });
                    g(i)
                },
                d = function() {
                    $(".templateDiv img").each(function() {
                        var t = this,
                            r = $(t).attr("isPreferred"),
                            u = $(t).attr("isDisposable"),
                            i = $(t).attr("searchId"),
                            f = $(t).attr("code");
                        u != "true" ? (r == "true" ? $(t).attr("src", "../../../../Content/imgs/xingxing1.png") : $(t).attr("src", "../../../../Content/imgs/xingxing2.png"), $(this).unbind("click").bind("click", function() {
                            (i == 0 || i == "" || i == null) && (i = f == "全部患者" ? -1 : -2);
                            o.updatePreferred(i).success(function(t) {
                                t && n.initSearchConfigs()
                            })
                        })) : $(t).parent().html("")
                    });
                    $(".templateDiv .editBtn").each(function() {
                        var t = this,
                            i = $(t).attr("isDisposable");
                        i != "true" ? $(this).unbind("click").bind("click", function() {
                            var t = $(this).attr("searchId");
                            n.openSearchConfigDialog(t)
                        }) : $(t).parent().html("")
                    });
                    $(".templateDiv .delBtn").each(function() {
                        var t = this,
                            i = $(t).attr("isDefault"),
                            r = $(t).attr("isDisposable");
                        r != "true" ? i == "true" ? $(t).hide() : $(this).unbind("click").bind("click", function() {
                            u.confirm("信息", "确定要删除吗！").then(function() {
                                var i = $(t).attr("searchId");
                                o.deleteSearchConfig(i).success(function(t) {
                                    t && (f.success("删除成功!"), n.searchConfigs = _.filter(n.searchConfigs, function(n) {
                                        return n.id != i
                                    }), l())
                                })
                            })
                        }) : $(t).parent().html("")
                    })
                },
                v = function() {
                    $(t).find("#patientList").html("");
                    var i = t.find("#searchDropDown").data("kendoDropDownList");
                    n.searchConfig = _.find(n.searchConfigs, function(n) {
                        return n.name == i.text()
                    });
                    n.searchConfig && n.onSearch()
                },
                g = function(i) {
                    var r = _.find(n.searchConfigs, function(n) {
                            return n.isPreferred
                        }),
                        u;
                    i && (r = _.find(n.searchConfigs, function(n) {
                        return n.name == i.name
                    }));
                    r && (u = t.find("#searchDropDown").data("kendoDropDownList"), u.select(function(n) {
                        return n.name === r.name
                    }))
                };
            (function() {
                n.initSearchConfigDropDown = l;
                n.search = v;
                n.commands = c;
                n.onCommandClick = b;
                n.refreshGrid = a;
                n.$watch("searchData.items", function() {
                    n.searchData && (a(), n.pageChage = !1)
                });
                n.$watch("searchConfigs", function() {
                    n.searchConfigs && (l(), v())
                });
                n.$on("$destroy", function() {
                    h.dispose()
                })
            })()
        }
    }
}]);
patientModule.directive("patientPhotoView", ["$log", "$timeout", "$q", "enums", "practiceSvc", "loginContext", "aresNotification", function(n, t, i, r, u, f, e) {
    "use strict";
    return {
        restrict: "E",
        replace: !0,
        templateUrl: "/app/patient/views/patient-photo/patient-photo-view.html",
        link: function(n, r) {
            var o = null,
                u, h, c, s, a = function() {
                    h != null && (h.stop && h.stop(), u.src = "");
                    c != null && c.stop && c.stop()
                },
                v = function() {
                    var t = i.defer();
                    return u = r.find("#video")[0], navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia, navigator.getUserMedia ? navigator.getUserMedia({
                        video: !0,
                        audio: !1
                    }, function(i) {
                        var r = window.URL || window.webkitURL;
                        try {
                            u.srcObject = i
                        } catch (f) {
                            u.src = r ? r.createObjectURL(i) : i
                        }
                        u.play();
                        h = i;
                        c = i.getTracks()[0];
                        n.cameraStatus.initialized = !0;
                        t.resolve(!0)
                    }, function(n) {
                        e.error("调用摄像头出错. (错误代码: " + n.message + ")");
                        t.reject()
                    }) : (e.error("对不起,您的浏览器不支持"), t.reject()), t.promise
                },
                y = function(t) {
                    n.pictureInputSource = t;
                    t == "cameraInput" && l()
                },
                p = function(t, i) {
                    var r = f.apiToken,
                        u = f.tokenType;
                    i.url = f.apiHost + "/api/v1/patient-photo?patientId=" + n.patientId;
                    i.headers = i.headers || {};
                    i.headers.Authorization = u + " " + r;
                    i.submit()
                },
                w = function() {},
                b = function() {},
                k = function(t, i) {
                    var r = parseInt(i.loaded / i.total * 100, 10);
                    n.progressBarPercentage = r + "%"
                },
                d = function(t, i) {
                    var r, u;
                    if (i.result != null && typeof i.result == "object") {
                        r = {};
                        for (u in i.result) r[u] = i.result[u];
                        r.type = "preview"
                    }
                    n.picture = r;
                    n.progressBarPercentage = "0%"
                },
                g = function() {
                    n.progressBarPercentage = "0%";
                    e.error("文件上传失败！")
                },
                nt = function() {
                    r.find("#pictureUploadPanel").click()
                },
                tt = function() {
                    return "/app/patient/views/patient-photo/upload-photo-item.html"
                },
                l = function() {
                    n.cameraStatus.initialized ? n.cameraStatus.action = "taking" : v().then(function() {
                        n.cameraStatus.action = "taking"
                    })
                },
                it = function() {
                    var e = r.find("#video"),
                        s = r.find("#canvas"),
                        i = e.width(),
                        f = e.height(),
                        h, c;
                    s.attr("width", i);
                    s.attr("height", f);
                    h = document.getElementById("canvas");
                    c = h.getContext("2d");
                    c.drawImage(u, 0, 0, i, f);
                    n.cameraStatus.action = "taked";
                    t(function() {
                        n.isJcropLoaded && (o ? o.setSelect([0, 0, i, f]) : o = $.Jcrop("#canvas", {
                            setSelect: [0, 0, i, f],
                            keySupport: !1,
                            onSelect: rt,
                            allowSelect: !1
                        }))
                    })
                },
                rt = function(n) {
                    s = n
                },
                ut = function() {
                    var i = document.getElementById("canvas"),
                        r = i.getContext("2d");
                    r.drawImage($("#canvas")[0], s.x, s.y, s.w, s.h, 0, 0, i.width, i.height);
                    t(function() {
                        var u = f.apiToken,
                            s = f.tokenType,
                            r = i.toDataURL("image/png");
                        r = r.replace("data:image/png;base64,", "");
                        $.ajax({
                            url: f.apiHost + "/api/v1/pictureCanvas?patientId=" + n.patientId,
                            data: '{ "data" : "' + r + '" }',
                            type: "post",
                            beforeSend: function(n) {
                                n.setRequestHeader("Authorization", s + " " + u);
                                n.setRequestHeader("Content-Disposition", 'attachment; filename="377adab44aed2e73635d952d8501a18b87d6fa7f.png"')
                            },
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function(i) {
                                i && (e.success("照片上传成功！"), n.initPicture(i.id), t(function() {
                                    n.cameraStatus.action = "saved"
                                }))
                            }
                        });
                        o && o.release()
                    })
                };
            (function() {
                n.pictureInputSource = "pictureInput";
                n.cameraStatus = {
                    initialized: !1,
                    action: null
                };
                n.isJcropLoaded = !1;
                n.closeCamera = a;
                n.onClickCamera = l;
                n.saveCamera = ut;
                n.uploadStart = w;
                n.uploadStop = b;
                n.uploadProgressed = k;
                n.uploadFinished = d;
                n.uploadFailed = g;
                n.addUpload = p;
                n.onClickFileDialog = nt;
                n.buildImageTemplateUrl = tt;
                n.takePhoto = it;
                n.changePictureInputSource = y;
                Ares.Loader.loadJs("/SublimeText3Project/yayi/js/jquery.Jcrop.min.js", function() {
                    Ares.Loader.loadCss("/SublimeText3Project/yayi/css/jquery.Jcrop.min.css", function() {
                        t(function() {
                            n.isJcropLoaded = !0
                        })
                    })
                })
            })()
        }
    }
}]);
patientModule.directive("uploadPhotoItem", ["$log", "$timeout", "$state", function() {
    return {
        restrict: "A",
        scope: {
            patientId: "=",
            add: "&",
            send: "&",
            start: "&",
            stop: "&",
            fail: "&",
            destroy: "&",
            done: "&",
            uploadprogress: "&"
        },
        link: function(n, t) {
            function i(n, t) {
                var i = {
                    dataType: "json",
                    type: "POST",
                    sequentialUploads: !0,
                    autoUpload: !0,
                    multipart: !1
                };
                n.add && (i.add = function(t, i) {
                    n.$apply(function() {
                        n.add({
                            e: t,
                            data: i
                        })
                    })
                });
                n.fail && (i.fail = function(t, i) {
                    n.$apply(function() {
                        n.fail({
                            e: t,
                            data: i
                        })
                    })
                });
                n.done && (i.done = function(t, i) {
                    n.$apply(function() {
                        n.done({
                            e: t,
                            data: i
                        })
                    })
                });
                n.uploadprogress && (i.progress = function(t, i) {
                    n.$apply(function() {
                        n.uploadprogress({
                            e: t,
                            data: i
                        })
                    })
                });
                t.fileupload(i)
            }(function() {})(i(n, t))
        }
    }
}]);